How to combine WHERE clauses in Eloquent

前端 未结 5 922
轻奢々
轻奢々 2021-01-13 15:27

I would like to have this kind of query in Eloquent:

SELECT * FROM table WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)

I\'ve been

相关标签:
5条回答
  • 2021-01-13 15:51

    Try THis:

    Table::where(function($query){
            $query->where('status', 1)
                ->orWhere('type', 2)
                ->orWhere('type', 3);
    });
    
    0 讨论(0)
  • 2021-01-13 15:52

    you can try parameter grouping in where to achieve what you want.

    Table::where('status', 1)->where(function ($query) {
                $query->where('type', 2)
                      ->orWhere('type', 3)
                      ->orWhere('type',4);})
    

    For more info check laravel Query builder documentation.

    0 讨论(0)
  • 2021-01-13 15:57

    Eloquent allows nested parameter groupings passing a Closure as the argument of where, orWhere, or the undocumented but more expressive whereNested:

    Table::where('status', 1)
        ->whereNested(function ($query) {
            $query->where('type', 2)
                  ->orWhere('type', 3)
                  ->orWhere('type', 4);
        });
    
    0 讨论(0)
  • 2021-01-13 16:03

    You may run a raw query and type exactly what you want: See: https://laravel.com/docs/5.2/database#running-queries

    0 讨论(0)
  • 2021-01-13 16:08

    To group where clauses like that, you need to pass a closure to the where() method, and add your grouped conditions inside the closure. So, your code would look something like:

    Table::where('status', 1)->where(function ($q) {
        return $q->where('type', 2)->orWhere('type', 3)->orWhere('type', 4);
    });
    

    This will generate the SQL:

    SELECT * FROM tables WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)
    
    0 讨论(0)
提交回复
热议问题