【发布时间】:2017-03-15 15:06:27
【问题描述】:
我正在使用 Eloquent 构建一个应用程序并遇到了麻烦,我正在使用多对多 Pivot 关系。 参考:https://laravel.com/docs/5.0/eloquent#many-to-many
用户模型
- 身份证
- 用户名
榜样
- 身份证
- 角色名称
用户角色模型(数据透视表)
- 身份证
- user_id
- role_id
如果我想获取所有角色 ID 为 1 的用户,我会简单:
$users = $app->users->with('roles')->has('roles')
->whereHas('roles' function($query) {
$query->where('role_id', 1);
})
->get();
有了这个,我可以成功获取所有 Role id = 1 的用户。
[问题] 现在我需要使用Role id = 1 AND Role id = 2 获取所有用户(在我的情况下是管理员和版主)
我试过运行这个:
$users = $app->users->with('roles')->has('roles')
->whereHas('roles' function($query) {
$query->where('role_id', 1);
})
->whereHas('roles' function($query) {
$query->where('role_id', 2);
})
->get();
但是耗尽了我的 PHP 执行时间,有没有正确的方法来处理这个问题?我真的希望有有效的方法来做到这一点。
谢谢
【问题讨论】:
-
对于机器人角色 ID,不应该是 OR 而不是 AND 吗?
-
@SougataBose 你好!我相信它的 AND,因为数据透视模型表对于单个 user_id 有多个 role_id,我希望实现的是获得所有 id
2 AND 3都在 role_id 中的用户
标签: php mysql arrays laravel-5 eloquent