laravel 雄辩的条件 where 过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26750285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent conditional where filter
提问by u976108
If I have a variable that is optional, and I only want to have it search on it if it is defined, I know that I can do this, but is there a way to define the function elsewhere, so I don't need to rewrite the same anonymous function over and over again? Or are the any other good alternatives to going about solving this problem?
如果我有一个可选的变量,并且我只想在它被定义的情况下搜索它,我知道我可以做到这一点,但是有没有办法在别处定义函数,所以我不需要一遍又一遍地重写同一个匿名函数?或者还有其他好的替代方法来解决这个问题吗?
.......->where(function($query) use ($gender){
if ($gender) {
$query->where('gender', '=', $gender);
}
})->get();
回答by Arne De Smedt
Since Laravel 5.2.27, you can use conditional clauses
从 Laravel 5.2.27 开始,您可以使用条件子句
For example:
例如:
->when($gender, function($query) use ($gender) {
$query->where('gender', '=', $gender);
})
->get();
回答by Laurence
You could use a dynamic scope
您可以使用动态范围
class User extends Eloquent {
public function scopeGender($query, $gender)
{
if ($gender) {
return $query->whereGender($gender);
}
return $query;
}
}
Then throughout your application
然后在整个申请过程中
...->gender($gender)->get();