Combining AND/OR eloquent query in Laravel

后端 未结 4 1741
温柔的废话
温柔的废话 2020-12-14 03:29

How can I write following or similar kind of queries using Eloquent?

SELECT * FROM a_table WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1 AND d = 5

相关标签:
4条回答
  • 2020-12-14 03:30

    In Laravel 5.1+ this will also do the job and looks cleaner:

    Model::where(function($query) {
        $query->where('a', 'like', 'keyword');
        $query->or_where('b', 'like', 'keyword');
    })->where('c', '=', '1')->get();
    
    0 讨论(0)
  • 2020-12-14 03:40

    You can nest where clauses : http://laravel.com/docs/database/fluent#nested-where

    Model::where(function($query)
    {
        $query->where('a', 'like', 'keyword');
        $query->or_where('b', 'like', 'keyword');
    })
    ->where('c', '=', '1');
    

    This should produce : SELECT * FROM models WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1

    0 讨论(0)
  • 2020-12-14 03:48

    For a more accurate answer to the example:

    $val = '%keyword%';
    
    A_Table_Model::where(function($query) use ($val)
    {
        $query->where('a', 'like', $val);
        $query->or_where('b', 'like', $val);
    })
    ->where('c', '=', 1)
    ->where('d', '=', 5)
    ->get();
    

    Note: This is Laravel 3 syntax, use camelCase orWhere() for Laravel 4

    0 讨论(0)
  • 2020-12-14 03:55

    You can use DB::raw() in the first where() to put in the like/or statement.

    0 讨论(0)
提交回复
热议问题