【发布时间】:2015-09-16 13:27:40
【问题描述】:
我正在构建一个有用户的系统。用户有角色,角色有行动。我的模型设置如下:
用户
/**
* 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
为什么这不起作用?
【问题讨论】:
-
使用我的答案here,我认为它很有用,但至少没有考虑投票。 :(
-
你的
$user变量有什么,是App\User::all()吗?
标签: php laravel laravel-4 laravel-5