vd/app/Models/Permission/Role.php
2018-11-06 16:07:41 +08:00

72 lines
1.7 KiB
PHP

<?php
namespace App\Models\Permission;
use App\Models\Account\Account;
use Dipper\Foundation\Core\Model;
use App\Exceptions\NotExistException;
use Illuminate\Database\Eloquent\Builder;
use Dipper\Foundation\Nestedset\NodeTrait;
use App\Models\Permission\Traits\HasPermissions;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use App\Models\Permission\Traits\RefreshesPermissionCache;
/**
* 角色
*/
class Role extends Model
{
use NodeTrait, HasPermissions, RefreshesPermissionCache;
protected $table = 'roles';
/**
* Get the hidden attributes for the model.
*
* @return array
*/
public function getHidden()
{
return [$this->getLftName(), $this->getRgtName()];
}
/**
* A role belongs to some users of the model associated.
*/
public function accounts(): BelongsToMany
{
return $this->belongsToMany(Account::class, 'account_has_roles', 'role_id', 'account_id');
}
public static function findById(int $id): Role
{
$role = static::where('id', $id)->first();
if (!$role) {
throw new NotExistException('角色不存在');
}
return $role;
}
/**
* Determine if the user may perform the given permission.
*
* @param string|Permission $permission
*
* @return bool
*/
public function hasPermissionTo($permission): bool
{
if (is_string($permission)) {
$permission = app(Permission::class)->findByName($permission);
}
if (is_int($permission)) {
$permission = app(Permission::class)->findById($permission);
}
return $this->permissions->contains('id', $permission->id);
}
}