在 Laravel 5.2 中使用 orWhere 查询范围

Query scope using orWhere in Laravel 5.2

使用 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');

不过没用。它只是 returns 所有记录,包括具有其他状态名称的记录。

它并没有做完全相同的事情。在 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');
        });
    });
}