You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.8 KiB

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use OwenIt\Auditing\Contracts\Auditable;
use Spatie\Permission\Traits\HasRoles;
class Admin extends Authenticatable implements Auditable
{
use SoftDeletes;
use Notifiable;
use HasRoles;
use HasApiTokens;
use FilterRequestColumnModelTrait;
use \OwenIt\Auditing\Auditable;
protected $table = "admins";
private $guard = "admin";
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $guarded = [
'id'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token'
];
public function syncRoles($roles)
{
$model_has_roles = config("permission.table_names.model_has_roles");
DB::table($model_has_roles)->where(["model_type" => self::class, "model_id" => $this->id])->delete();
$admin_roles = [];
foreach ($roles as $role) {
$admin_roles[] = [
"model_type" => self::class,
"model_id" => $this->id,
"role_id" => $role->id
];
}
return DB::table($model_has_roles)->insert($admin_roles);
}
public function department()
{
return $this->belongsTo(Department::class);
}
public function role()
{
return $this->belongsToMany(Role::class, 'model_has_roles', 'model_id', 'role_id')->where('model_type', 'App\Models\Admin');
}
/**
* 获取当前用户有数据权限的部门
*/
public static function roleAllowAdminIds($admin)
{
$minAllowLevel = $admin->roles->min('allow_level');
$departmentIds = [];
if ($minAllowLevel == 0) {
// 全部数据权限
$departmentIds = Department::pluck('id');
}
if ($minAllowLevel == 1) {
// 部门和下级部门权限
$departmentIds = Department::where('leader_id', $admin->id)->orWhere('id', $admin->department_id)->pluck('id');
}
if ($minAllowLevel == 2) {
// 自己的数据权限
$departmentIds = [];
}
return $departmentIds;
}
}