Laravel查询范围组合
Laravel query scope combination
我正在使用 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();
时,它会 returns 所有结果,并且不会按 S1
和 S2
进行过滤。另请注意,我这样做时没有问题
SomeModel::where('field1', '=', 'S1')->where('field2', '=', 'S2')->get()
那么为什么要在这里确定查询范围并执行任何操作?
由于您的实际作用域包含 OR 条件,因此您应该使用嵌套的 where 来确保它们得到正确解释。 Laravel 将括号括起来。
public function scopeS1($query) {
return $query->where(function($q){
$q->where('field1', '=', 'S1')
->orWhere('foo', '=', 'bar');
});
}
// and the same for scopeS2...
我正在使用 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();
时,它会 returns 所有结果,并且不会按 S1
和 S2
进行过滤。另请注意,我这样做时没有问题
SomeModel::where('field1', '=', 'S1')->where('field2', '=', 'S2')->get()
那么为什么要在这里确定查询范围并执行任何操作?
由于您的实际作用域包含 OR 条件,因此您应该使用嵌套的 where 来确保它们得到正确解释。 Laravel 将括号括起来。
public function scopeS1($query) {
return $query->where(function($q){
$q->where('field1', '=', 'S1')
->orWhere('foo', '=', 'bar');
});
}
// and the same for scopeS2...