Admin.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Models;
  3. use App\Constants\HttpStatus;
  4. use Illuminate\Contracts\Auth\Authenticatable;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Exception;
  7. use Illuminate\Database\Eloquent\Builder;
  8. /**
  9. * Admin
  10. * @mixin Builder
  11. * @method static Builder|static where($column, $operator = null, $value = null, $boolean = 'and')
  12. * @property mixed $id
  13. */
  14. class Admin extends Model implements Authenticatable
  15. {
  16. use \Illuminate\Auth\Authenticatable; // 使用 Auth 认证相关功能
  17. protected $table = 'admin';
  18. protected $hidden = ['password', 'created_at', 'updated_at'];
  19. protected $fillable = ['username','nickname','password','sex','cellphone','email','remarks', 'created_at', 'updated_at'];
  20. protected $appends = ['roles_ids', 'roles_names'];
  21. public static function login($username, $password)
  22. {
  23. $map = [];
  24. $map[] = ['username', '=', $username];
  25. $user = new Admin();
  26. $user = $user->where($map)->first();
  27. if (!$user) throw new Exception('', HttpStatus::USER_DOES_NOT_EXIST);
  28. if (!password_verify($password, $user->password)) throw new Exception('', HttpStatus::PASSWORDS_ERROR);
  29. return $user;
  30. }
  31. public function roles()
  32. {
  33. return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
  34. }
  35. public function getRolesIdsAttribute()
  36. {
  37. return $this->roles->pluck('id')->toArray();
  38. }
  39. public function getRolesNamesAttribute()
  40. {
  41. return $this->roles->pluck('display_name')->toArray();
  42. }
  43. public function getId()
  44. {
  45. return $this->id;
  46. }
  47. }