雄辩的条件过滤器 [英] Eloquent conditional where filter
本文介绍了雄辩的条件过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个可选的变量,并且只想在定义后对其进行搜索,我知道我可以做到这一点,但是有一种方法可以在其他地方定义该函数,所以我不这样做是否需要一遍又一遍重写相同的匿名函数?还是解决这个问题的其他好选择?
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();
推荐答案
您可以使用动态范围
class User extends Eloquent {
public function scopeGender($query, $gender)
{
if ($gender) {
return $query->whereGender($gender);
}
return $query;
}
}
然后在整个应用程序中
...->gender($gender)->get();
这篇关于雄辩的条件过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文