【问题标题】:eloquent multiple whereHas('pivot_table_X') AND whereHas('pivot_table_X')雄辩的多个 whereHas('pivot_table_X') AND whereHas('pivot_table_X')
【发布时间】: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


【解决方案1】:

你可以试试:

$users = $app->users->with('roles')
           ->whereHas('roles' function($query) {
              $query->where('role_id', 1)
                    ->where('role_id', 2);
          })
          ->get();

我故意删除了->has('roles'),因为我们在角色表上使用了whereHas(),所以has 将没有用处。它的工作原理是一样的。

【讨论】:

  • 抱歉,但我不认为 SQL 会解决它,它会在数据透视表中查找“role_id”为 1 和 2 的“单”行,这是不可能的。试过了,ofc,它不会从模型中返回任何对象。
猜你喜欢
  • 1970-01-01
  • 2014-06-02
  • 2018-04-02
  • 2021-12-24
  • 1970-01-01
  • 2015-07-25
  • 2019-01-22
  • 2022-01-27
  • 1970-01-01
相关资源
最近更新 更多