Student.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace App\Models;
  3. use App\Services\StudentIdService;
  4. use Illuminate\Database\Eloquent\Factories\HasFactory;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. class Student extends Model
  8. {
  9. use HasFactory;
  10. protected $table = 'students';
  11. protected $primaryKey = 'student_id';
  12. public $incrementing = false;
  13. protected $keyType = 'string';
  14. protected $fillable = [
  15. 'student_id',
  16. 'name',
  17. 'grade',
  18. 'class_name',
  19. 'teacher_id',
  20. 'remark',
  21. 'student_report_pdf_url', // 学生学情报告PDF URL
  22. ];
  23. protected $casts = [
  24. 'created_at' => 'datetime',
  25. 'updated_at' => 'datetime',
  26. 'student_report_pdf_url' => 'string',
  27. ];
  28. protected static function boot()
  29. {
  30. parent::boot();
  31. // 在创建学生时自动生成ID并创建用户记录
  32. static::creating(function (Student $student) {
  33. if (empty($student->student_id)) {
  34. $student->student_id = StudentIdService::generateStudentId();
  35. }
  36. // 创建对应的用户记录(需要在学生记录之前创建,因为存在外键约束)
  37. $existingUser = \App\Models\User::where('user_id', $student->student_id)->first();
  38. if (!$existingUser) {
  39. \App\Models\User::create([
  40. 'user_id' => $student->student_id,
  41. 'username' => $student->student_id,
  42. 'password_hash' => \Hash::make('password123'), // 默认密码,实际使用时应该修改
  43. 'role' => 'student',
  44. 'full_name' => $student->name,
  45. 'email' => $student->student_id . '@student.edu',
  46. 'is_active' => 1,
  47. ]);
  48. }
  49. });
  50. // 在学生数据变更后清除缓存
  51. static::saved(function (Student $student) {
  52. \App\Filament\Resources\StudentResource::clearCaches();
  53. });
  54. static::deleted(function (Student $student) {
  55. \App\Filament\Resources\StudentResource::clearCaches();
  56. });
  57. }
  58. public function teacher(): BelongsTo
  59. {
  60. return $this->belongsTo(Teacher::class, 'teacher_id', 'teacher_id');
  61. }
  62. public function user(): BelongsTo
  63. {
  64. return $this->belongsTo(User::class, 'student_id', 'user_id');
  65. }
  66. /**
  67. * 获取学生的试卷列表
  68. */
  69. public function papers()
  70. {
  71. return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id');
  72. }
  73. /**
  74. * 获取学生最近生成的试卷
  75. */
  76. public function recentPapers($limit = 10)
  77. {
  78. return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id')
  79. ->orderBy('created_at', 'desc')
  80. ->limit($limit);
  81. }
  82. }