Eloquent conditional where filter

北城以北 提交于 2020-01-03 09:00:08

问题


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();

回答1:


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();



回答2:


Since Laravel 5.2.27, you can use conditional clauses

For example:

->when($gender, function($query) use ($gender) {
        $query->where('gender', '=', $gender);
      })
->get();


来源:https://stackoverflow.com/questions/26750285/eloquent-conditional-where-filter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!