首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在laravel 5.3中检查模型实例是否附加到相关的模型实例?

如何在laravel 5.3中检查模型实例是否附加到相关的模型实例?
EN

Stack Overflow用户
提问于 2016-09-25 01:01:40
回答 2查看 986关注 0票数 0

我对rolespermissions模型有多对多的关系。我有一个动作控制器,用于附加和分离用户的权限。如何检查某些权限是否被分离到某个角色?

控制器:

代码语言:javascript
运行
复制
class RolePermissionController extends Controller
{
    // POST /roles/1/permissions/2/sync
    // BODY {isAllowed: true} 
    // $role - instance of role model with id == 1
    // $permission - instance of permission model with id == 2
    // roles and permissions has many to many relationship
    public function synchronize(Request $request, Role $role, Permission $permission)
    {
        $this->authorize($permission);

        $this->validate($request, [
            'isAllowed' => 'required|boolean'
        ]);

        // I want to check here if the permission is attached to the role

        if ($request->input('isAllowed')) {
            $role->perms()->attach($permission);
        } else {
            $role->perms()->detach($permission);
        }

    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-25 05:38:20

$role->whereHas('perms', function($query) use($permission) { $query->where('perms.id', $permission->id); })->count();

或者,假设您已经加载了权限:

$role->perms->contains(function($value) use($permission) { return $value->id == $permission->id; })

票数 1
EN

Stack Overflow用户

发布于 2018-05-13 00:24:53

我简单地使用第一个模型的关联方法来访问连接表的查询构建器,然后请求关联模型的列的计数。在你的案例中,我认为:

$role->->where(‘permission_id’,$permission->id)perms()->count()>0

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39678845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档