【问题标题】:Query scope using orWhere in Laravel 5.2在 Laravel 5.2 中使用 orWhere 查询范围
【发布时间】:2016-01-21 10:33:36
【问题描述】:

使用 Laravel 5.2,我的模型具有以下查询范围:

public function scopeInProcess($query) {
    return $query->whereHas(
        'ApplicationStatus', function($query) {
            $query->whereRaw('(name = "New" OR name = "In-process")');
        }
    );
}

以上工作正常,但我只开始使用whereRaw(),因为我无法让orWhere() 像文档中描述的那样工作。

据我所知,这应该与whereRaw() 完全相同:

$query->where('name', 'New')->orWhere('name' , 'In-process');

但它不起作用。它只返回所有记录,包括具有其他状态名称的记录。

【问题讨论】:

  • 你是否在 "$query->where(.....);" 之前添加了 "return" ?

标签: php laravel laravel-5 eloquent laravel-5.2


【解决方案1】:

它没有做完全相同的事情。在您的whereRaw() 中,您已将两个条件都放在括号中,以便将它们组合在一起。这就是你想要的。但是,where()->orWhere() 不会自动执行此操作。

要获得所需的功能,您需要对条件进行分组,就像在 whereRaw() 中所做的那样。为此,您可以将闭包传递给 where() 方法,如下所示:

public function scopeInProcess($query) {
    return $query->whereHas('ApplicationStatus', function($query) {
        $query->where(function($q) {
            $q->where('name', 'New')->orWhere('name', 'In-process');
        });
    });
}

【讨论】:

猜你喜欢
  • 2017-05-30
  • 2015-02-22
  • 1970-01-01
  • 2015-09-05
  • 2020-01-01
  • 2021-02-11
  • 2023-04-05
  • 2017-12-17
  • 2015-06-13
相关资源
最近更新 更多