Laravel嵌套关系


Laravel nested relationship where

我正在构建一个有用户的系统。用户有角色,角色有动作。我的模型是这样设置的:

用户

/**
 * The roles that belong to the user.
 *
 * @return Object
 */
public function roles()
{
    return $this->belongsToMany('App'Models'User'Role')->withTimestamps();
}

/**
 * The actions that belong to the role.
 *
 * @return Object
 */
public function actions() 
{
    return $this->belongsToMany('App'Models'User'Action')->withPivot('path');
}
/**
 * The users that belong to the role.
 *
 * @return Object
 */
public function users()
{
    return $this->belongsToMany('App'Models'User'User');
}

/**
 * The roles that belong to the action.
 *
 * @return Object
 */
public function roles() 
{
    return $this->belongsToMany('App'Models'User'Role');
}

我正在尝试使用以下命令搜索用户的操作:

$user->whereHas('roles.actions', function($query) use ($id, $path, $method){ 
        $query->where('user.id', $id);
        $query->where('action.path', $path);
        $query->where('action.method', $method);
})->get();

但是,由于某种原因返回的对象是空的(没有返回任何行)。如果我删除$query->where('action.path', $path);,它可以工作,但这是毫无意义的,因为我需要那部分。

生成的SQL是:

select * from `user` 
    where `user`.`cust_id` = 1 
    and (
            select count(*) from `role` 
            inner join `role_user` on `role`.`id` = `role_user`.`role_id` 
            where `role`.`cust_id` = 1 
            and `role_user`.`user_id` = `user`.`id` 
            and 
            (
                select count(*) from `action` 
                inner join `action_role` on `action`.`id` = `action_role`.`action_id` 
                where `action`.`cust_id` = 1 
                and `action_role`.`role_id` = `role`.`id` 
                and `user`.`id` = 1 
                and `action`.`path` = '/admin/users/administrators/{id}/changePassword' 
                and `action`.`method` = 'GET' 
                and `action`.`cust_id` = 1
            ) >= 1 
            and `role`.`cust_id` = 1
        ) >= 1

我的users表包含以下数据:

id    cust_id    name
1     1          John Smith

我的动作表包含以下数据:

id    cust_id    path                                               method
1     1          /admin/users/administrators/{id}/changePassword    GET

为什么不工作?

我真的不明白这是一个有效的查询,因为您在子查询中查询users表中的列,而不连接任何与用户有关的内容。

试试这个

$user->whereHas('roles.actions', function($query) use ( $path, $method){
    $query->where('path', $path);
    $query->where('method', $method);
})->find($id);

删除->withPivot('path');并重试

正如您的问题所指出的,另一个这里 path不是您的数据透视表action_role的额外属性-保持模型RoleAction之间的关系。

它是action表的一个属性。因此,使用withPivot('path'),您是在pivot(即action_role)上定义了不存在的额外属性,因此根本没有必要。

关于包含$query->where('action.path', $path)行所得到的空集,最可能的原因是$path变量中提供了不正确的null值。再次检查是否有正确的值。

注意:据我所知,你不能像那样在$user上执行whereHas(尽管我不太确定它持有什么)。即使$user是用户的集合(由App'Models'User::all() 获得的),使用whereHas的适当方法是在App'User::whereHas(...或关系等模型上使用它。