'datetime', 'updated_at' => 'datetime', 'student_report_pdf_url' => 'string', ]; protected static function boot() { parent::boot(); // 在创建学生时自动生成ID并创建用户记录 static::creating(function (Student $student) { if (empty($student->student_id)) { $student->student_id = StudentIdService::generateStudentId(); } // 创建对应的用户记录(需要在学生记录之前创建,因为存在外键约束) $existingUser = \App\Models\User::where('user_id', $student->student_id)->first(); if (!$existingUser) { \App\Models\User::create([ 'user_id' => $student->student_id, 'username' => $student->student_id, 'password_hash' => \Hash::make('password123'), // 默认密码,实际使用时应该修改 'role' => 'student', 'full_name' => $student->name, 'email' => $student->student_id . '@student.edu', 'is_active' => 1, ]); } }); // 在学生数据变更后清除缓存 static::saved(function (Student $student) { \App\Filament\Resources\StudentResource::clearCaches(); }); static::deleted(function (Student $student) { \App\Filament\Resources\StudentResource::clearCaches(); }); } public function teacher(): BelongsTo { return $this->belongsTo(Teacher::class, 'teacher_id', 'teacher_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'student_id', 'user_id'); } /** * 获取学生的试卷列表 */ public function papers() { return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id'); } /** * 获取学生最近生成的试卷 */ public function recentPapers($limit = 10) { return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id') ->orderBy('created_at', 'desc') ->limit($limit); } }