[英]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
我的用户表包含以下数据:
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');
然后再试一次
如您的问题所述,另外一个HERE path
不是数据透视表action_role
的额外属性-保持模型Role
和Action
之间的关系。
相反,它是action
表的属性。 因此,使用withPivot('path')
可以在pivot
上定义不存在的额外属性(即action_role
),因此根本不需要。
关于空集你,如果你有行$query->where('action.path', $path)
最可能的原因是不正确或null
值在您提供的$path
变量。 仔细检查是否具有正确的值。
注意: 据我所知,您不能像这样在$user
上执行whereHas
(尽管我不太确定它的whereHas
)。 即使$user
是$user
集合( 由App\\Models\\User::all()
),使用whereHas
的合适方法是在诸如App\\User::whereHas(...
或一个关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.