Php Laravel嵌套关系,其中
我正在构建一个有用户的系统。用户有角色,角色有动作。我的模型设置如下: 用户Php Laravel嵌套关系,其中,php,laravel,laravel-4,laravel-5,Php,Laravel,Laravel 4,Laravel 5,我正在构建一个有用户的系统。用户有角色,角色有动作。我的模型设置如下: 用户 /** * The roles that belong to the user. * * @return Object */ public function roles() { return $this->belongsToMany('App\Models\User\Role')->withTimestamps(); } 角色 /** * The actions that belong
/**
* 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
我的操作表包含以下数据:
id cust_id name
1 1 John Smith
id cust_id path method
1 1 /admin/users/administrators/{id}/changePassword GET
为什么不起作用?用pivot('path')删除->
并重试我真的不明白这是一个有效的查询,因为您正在子查询中的users
表中查询一列,而该列没有连接任何与用户有关的内容
试试这个
$user->whereHas('roles.actions', function($query) use ( $path, $method){
$query->where('path', $path);
$query->where('method', $method);
})->find($id);
正如您在问题中所指出的,另一个路径
不是透视表动作角色
的额外属性,它保持着模型角色
和动作
之间的关系
相反,它是操作
表的一个属性。因此,使用with pivot('path')
可以在pivot
(即操作_角色
)上定义不存在的额外属性,因此根本不需要该属性
关于包含行$query->where('action.path',$path)
时得到的空集,最可能的原因是$path
变量中提供了不正确或null
值。仔细检查它是否具有正确的值
注意:据我所知,您不能像这样在$user
上执行whereHas
(尽管我不太确定它包含什么)。
即使<代码> $用户<代码>是一个用户集合(通过<代码> App\Meave\Auth::A/Office >获得),使用< <代码> > < <代码> >的适当方法是使用它,如“代码> App\Up:”……(…<代码/ >或一个关系。使用我的答案,我认为它是有用的,但至少不考虑投票。(您的$user
变量有什么,它是App\user::all()
?