我使用的是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();
时,它会返回所有结果,并且不会按S1
和S2
进行过滤。还要注意我做的时候没有问题
SomeModel::where('field1', '=', 'S1')->where('field2', '=', 'S2')->get()
那么为什么查询范围并在这里做任何事情?
答案 0 :(得分:3)
由于您的实际范围包含OR条件,您应该使用嵌套的位置以确保它们被正确解释。 Laravel将围绕括号括起来。
public function scopeS1($query) {
return $query->where(function($q){
$q->where('field1', '=', 'S1')
->orWhere('foo', '=', 'bar');
});
}
// and the same for scopeS2...