81 lines
1.6 KiB
PHP
81 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
|
|
class Role extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'name',
|
|
'slug',
|
|
'description',
|
|
'level',
|
|
'guard_name',
|
|
];
|
|
|
|
protected $casts = [
|
|
'level' => 'integer',
|
|
];
|
|
|
|
/**
|
|
* 权限关联
|
|
*/
|
|
public function permissions(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Permission::class, 'role_permissions');
|
|
}
|
|
|
|
/**
|
|
* 用户关联
|
|
*/
|
|
public function users(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(User::class, 'user_roles');
|
|
}
|
|
|
|
/**
|
|
* 同步权限
|
|
*/
|
|
public function syncPermissions(array $permissionIds): void
|
|
{
|
|
$this->permissions()->sync($permissionIds);
|
|
}
|
|
|
|
/**
|
|
* 分配权限
|
|
*/
|
|
public function givePermissionTo(Permission $permission): void
|
|
{
|
|
$this->permissions()->syncWithoutDetaching([$permission->id]);
|
|
}
|
|
|
|
/**
|
|
* 移除权限
|
|
*/
|
|
public function revokePermissionTo(Permission $permission): void
|
|
{
|
|
$this->permissions()->detach([$permission->id]);
|
|
}
|
|
|
|
/**
|
|
* 判断是否有某权限
|
|
*/
|
|
public function hasPermission(string $slug): bool
|
|
{
|
|
return $this->permissions()->where('slug', $slug)->exists();
|
|
}
|
|
|
|
/**
|
|
* 通过slug查找
|
|
*/
|
|
public static function findBySlug(string $slug): ?self
|
|
{
|
|
return static::where('slug', $slug)->first();
|
|
}
|
|
}
|