【问题标题】:Laravel 5.2 query scopes unexpected behavior with orWhereLaravel 5.2 查询范围与 orWhere 的意外行为
【发布时间】:2017-05-30 14:25:37
【问题描述】:

我使用的查询范围应该附加一个 orWhere 条件,但它附加了一个普通的 where(使用 AND)。如果我删除查询范围并将其直接放入,它确实会返回 OR 条件。

查询如下所示:

$query = MyModel::firstQueryScope()->secondQueryScope();

FirstQueryScope:

public function scopeFirstQueryScope($query){
    return $query->where('someAttribute', 0);
}

第二次查询范围:

public function scopeSecondQueryScope($query){
    return $query->orWhere('someOtherAttribute', 0);
}

以这种方式构建查询应该与以下内容相同:

$query = MyModel::where('someAttribute', 0)->orWhere('someOtherAttribute', 0);

但是第一种方法返回这个查询:

  • select * from MyModelTable where someAttribute = 0 AND (someOtherAttribute = 0)

第二种方法返回:

  • select * from MyModelTable where someAttribute = 0 OR someOtherAttribute = 0

我注意到两件事:

  1. 无论您调用 FirstQueryScope 或 SecondQueryScope 的顺序如何,它始终用括号括住 orWhere 范围。
  2. orWhere 方法仅在从查询范围调用时添加括号。

我做错了什么?或者这可能是 Eloquent 的错误?

注意:我正在构建的查询更加详细,但我已将其分解为这种简单性以验证我没有做任何奇怪的事情。

更新

我尝试调试 Eloquent 的构建过程,发现它添加了一个 嵌套的 where 并在其中添加了 orWhere 范围。同样,这只发生在将 orWhere 放在范围内时,但在添加简单的 where 时不会发生。 嵌套 where 负责将 orWhere 表达式括在圆括号内。

【问题讨论】:

标签: eloquent laravel-5.2


【解决方案1】:

我认为作用域本身是孤立的。

只需添加第三个作用域。

public function scopeFirstQueryOrSecondQuery($query){
    return $query->where('someAttribute', 0)
        ->orWhere('someOtherAttribute', 0);
}

-

MyModel::firstQueryOrSecondQuery()->get();

【讨论】:

  • 是的,我可以这样做,但我会复制我的代码。你是什​​么意思范围是孤立的?只要我知道他们不应该更改查询生成器范围。此外,仅当将 orWhere 添加到范围时才会发生这种情况。出于某种原因,Eloquent 正在添加一个 NestedWhere,但我无法追踪它的来源。
猜你喜欢
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多