【问题标题】:Avoid "where" clause grouping when applying multiple where clauses inside the same scope在同一范围内应用多个 where 子句时避免“where”子句分组
【发布时间】:2022-01-27 04:16:09
【问题描述】:

我的模型中有这个范围:

function extraFiltersScope($query){
    $query->where('first_name', 'test')->orWhere('name', 'testing');
    return $query;
}

我正在应用这样的子句:

$query = User::where('age', 30')->extraFilters()->toSql();

预期的 SQL 将是:

select * from users where age=30 and first_name='test' or name='testing'

我明白了:

select * from users where age=30 and (first_name='test' or name='testing')

这似乎是正常行为,因为两个“where”子句都在同一范围内应用。是否有解决方法告诉构建者现在将它们分组?

当然,我的逻辑比这复杂得多,否则我可以简单地为每个逻辑设置一个范围方法。我需要在同一范围内应用多个过滤器,但不能嵌套。

谢谢。

【问题讨论】:

  • 您使用的是什么数据库?如果我对 wheres 进行分组,我只能得到分组的输出
  • lagbox,我对这个问题进行了大量编辑。我找到了问题的原因,现在我需要知道是否有针对默认行为的解决方法。谢谢。
  • 这两个 SQL 查询完全相同; AND 的优先级高于 OR。你可以自己测试一下:SELECT 1=1 AND 2=2 OR 3=4 返回 1。

标签: laravel eloquent


【解决方案1】:

尝试使用 DB::raw

    $query->where(DB::raw("( age = 30 and first_name = 'test')"))
           ->where("name", "=", testing)
    return $query;

【讨论】:

  • 对不起,但我想你的回答正是我不想做的。我想避免括号。这是我需要的 SQL:select * from users where age=30 and first_name='test' or name='testing'
  • 我已经编辑了之前的答案。我认为使用它应该可以工作
猜你喜欢
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多