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

How to check if a model instance is attached to related model instance in laravel 5.3?

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

控制器:

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);
        }

    }
}

$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; })

我只是使用第一个模型的关联方法来访问连接的查询构建器 table,然后请求关联模型列的计数。对于你的情况,我认为:

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