Laravel查询范围组合



我正在使用Laravel 4.2查询范围,但遇到了问题。

我的模型:

class SomeModel extends Eloquent {
    public function scopeS1($query) {
        return $query->where('field1', '=', 'S1');
    }
    public function scopeS2($query) {
        return $query->where('field2', '=', 'S2');
    }
}

现在,当我这样做时SomeModel::s1()->s2()->get();它会返回所有结果,并且不会按S1S2进行过滤。另请注意,当我这样做时我没有问题

SomeModel::where('field1', '=', 'S1')->where('field2', '=', 'S2')->get()

那么为什么查询范围和在这里做任何事情呢?

由于您的实际作用域包含 OR 条件,因此您应该使用嵌套的 where 来确保它们被正确解释。拉拉维尔将用括号括起来。

public function scopeS1($query) {
    return $query->where(function($q){
        $q->where('field1', '=', 'S1')
          ->orWhere('foo', '=', 'bar');
    });
}
// and the same for scopeS2...

最新更新