catchAdmin/catch/permissions/model/HasPermissionsTrait.php

77 lines
1.7 KiB
PHP
Raw Normal View History

2020-04-29 17:37:45 +08:00
<?php
/**
* @filename HasPermissionsTrait.php
* @createdAt 2020/1/14
* @project https://github.com/yanwenwu/catch-admin
* @document http://doc.catchadmin.com
* @author JaguarJack <njphper@gmail.com>
* @copyright By CatchAdmin
* @license https://github.com/yanwenwu/catch-admin/blob/master/LICENSE.txt
*/
namespace catchAdmin\permissions\model;
trait HasPermissionsTrait
{
/**
*
* @time 2019年12月09日
* @return \think\model\relation\BelongsToMany
*/
public function permissions(): \think\model\relation\BelongsToMany
{
return $this->belongsToMany(Permissions::class, 'role_has_permissions', 'permission_id', 'role_id');
}
/**
*
* @time 2019年12月08日
* @param array $condition
* @param array $field
* @return mixed
*/
public function getPermissions($condition = [], $field = [])
{
return $this->permissions()
->when(!empty($field), function ($query) use ($field){
$query->field($field);
})
->when(!empty($condition), function ($query) use ($condition){
$query->where($condition);
})
->select();
}
/**
*
* @time 2019年12月08日
* @param array $permissions
* @return mixed
* @throws \think\db\exception\DbException
*/
2020-07-24 21:40:26 +08:00
public function attachPermissions(array $permissions)
2020-04-29 17:37:45 +08:00
{
if (empty($permissions)) {
2020-06-21 21:07:15 +08:00
return true;
2020-04-29 17:37:45 +08:00
}
sort($permissions);
return $this->permissions()->attach($permissions);
}
/**
*
* @time 2019年12月08日
2020-07-24 21:40:26 +08:00
* @param array $permissions
2020-04-29 17:37:45 +08:00
* @return mixed
*/
2020-07-24 21:40:26 +08:00
public function detachPermissions(array $permissions = [])
2020-04-29 17:37:45 +08:00
{
2020-07-24 21:40:26 +08:00
if (empty($permissions)) {
2020-06-21 21:07:15 +08:00
return $this->permissions()->detach();
2020-04-29 17:37:45 +08:00
}
2020-07-24 21:40:26 +08:00
return $this->permissions()->detach($permissions);
2020-04-29 17:37:45 +08:00
}
}