How to Create Multiple Where Clause Query Using Laravel Eloquent?

前端 未结 24 1080
一整个雨季
一整个雨季 2020-11-22 14:30

I\'m using the Laravel Eloquent query builder and I have a query where I want a WHERE clause on multiple conditions. It works, but it\'s not elegant.

E

24条回答
  •  囚心锁ツ
    2020-11-22 15:28

    Query scopes may help you to let your code more readable.

    http://laravel.com/docs/eloquent#query-scopes

    Updating this answer with some example:

    In your model, create scopes methods like this:

    public function scopeActive($query)
    {
        return $query->where('active', '=', 1);
    }
    
    public function scopeThat($query)
    {
        return $query->where('that', '=', 1);
    }
    

    Then, you can call this scopes while building your query:

    $users = User::active()->that()->get();
    

提交回复
热议问题