Student.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Repositories\Models\Mentor;
  3. use App\Repositories\Enums\Base\AdminTypeEnum;
  4. use App\Repositories\Enums\ModelStatusEnum;
  5. use App\Repositories\Models\Base\Admin;
  6. use App\Repositories\Models\Model;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Hash;
  9. class Student extends Model
  10. {
  11. /**
  12. * @var string
  13. */
  14. protected $table = 'mentor_students';
  15. protected $guarded = [];
  16. /**
  17. * The attributes excluded from the model's JSON form.
  18. *
  19. * @var array
  20. */
  21. protected $hidden = [];
  22. protected static function boot()
  23. {
  24. parent::boot(); // TODO: Change the autogenerated stub
  25. static::created(function (Student $model) {
  26. $admin = Admin::query()->create([
  27. 'username' => $model->account,
  28. 'password' => Hash::make($model->password),
  29. 'name' => $model->truename,
  30. 'type' => AdminTypeEnum::USER,
  31. 'status' => ModelStatusEnum::OK,
  32. 'email' => $model->email,
  33. 'shop_id' => $model->grade_id,
  34. ]);
  35. $admin->assignRole('student');
  36. DB::table('mentor_students')->where('id', $model->id)->update(['admin_id' => $admin->id]);
  37. });
  38. static::saved(function (Student $model) {
  39. $data = [
  40. 'username' => $model->account,
  41. 'name' => $model->truename,
  42. 'email' => $model->email,
  43. 'status' => $model->status,
  44. 'shop_id' => $model->grade_id,
  45. ];
  46. if ($model->isDirty('password')) {
  47. $data['password'] = Hash::make($model->password);
  48. }
  49. Admin::query()->where('type', AdminTypeEnum::USER)->where('id', $model->admin_id)->update($data);
  50. });
  51. static::deleted(function (Student $model) {
  52. Admin::query()->where('type', AdminTypeEnum::USER)->where('id', $model->admin_id)->delete();
  53. });
  54. }
  55. public function grade()
  56. {
  57. return $this->belongsTo(Grade::class)->select(['id', 'name']);
  58. }
  59. }