Student.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ];
  22. protected $casts = [
  23. 'created_at' => 'datetime',
  24. 'updated_at' => 'datetime',
  25. ];
  26. protected static function boot()
  27. {
  28. parent::boot();
  29. // 在创建学生时自动生成ID并创建用户记录
  30. static::creating(function (Student $student) {
  31. if (empty($student->student_id)) {
  32. $student->student_id = StudentIdService::generateStudentId();
  33. }
  34. // 创建对应的用户记录(需要在学生记录之前创建,因为存在外键约束)
  35. $existingUser = \App\Models\User::where('user_id', $student->student_id)->first();
  36. if (!$existingUser) {
  37. \App\Models\User::create([
  38. 'user_id' => $student->student_id,
  39. 'username' => $student->student_id,
  40. 'password_hash' => \Hash::make('password123'), // 默认密码,实际使用时应该修改
  41. 'role' => 'student',
  42. 'full_name' => $student->name,
  43. 'email' => $student->student_id . '@student.edu',
  44. 'is_active' => 1,
  45. ]);
  46. }
  47. });
  48. // 在学生数据变更后清除缓存
  49. static::saved(function (Student $student) {
  50. \App\Filament\Resources\StudentResource::clearCaches();
  51. });
  52. static::deleted(function (Student $student) {
  53. \App\Filament\Resources\StudentResource::clearCaches();
  54. });
  55. }
  56. public function teacher(): BelongsTo
  57. {
  58. return $this->belongsTo(Teacher::class, 'teacher_id', 'teacher_id');
  59. }
  60. public function user(): BelongsTo
  61. {
  62. return $this->belongsTo(User::class, 'student_id', 'user_id');
  63. }
  64. }