Admin.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. */
  13. class Admin extends Model implements Authenticatable
  14. {
  15. use \Illuminate\Auth\Authenticatable; // 使用 Auth 认证相关功能
  16. protected $table = 'admin';
  17. protected $hidden = ['password', 'created_at', 'updated_at'];
  18. protected $fillable = ['username','nickname','password','sex','cellphone','email','remarks', 'created_at', 'updated_at'];
  19. protected $appends = ['roles_ids', 'roles_names'];
  20. public static function login($username, $password)
  21. {
  22. $map = [];
  23. $map[] = ['username', '=', $username];
  24. $user = new Admin();
  25. $user = $user->where($map)->first();
  26. if (!$user) throw new Exception('', HttpStatus::USER_DOES_NOT_EXIST);
  27. if (!password_verify($password, $user->password)) throw new Exception('', HttpStatus::PASSWORDS_ERROR);
  28. return $user;
  29. }
  30. public function roles()
  31. {
  32. return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
  33. }
  34. public function getRolesIdsAttribute()
  35. {
  36. return $this->roles->pluck('id')->toArray();
  37. }
  38. public function getRolesNamesAttribute()
  39. {
  40. return $this->roles->pluck('display_name')->toArray();
  41. }
  42. }