Laravel query builder with AND in query
Asked Answered
A

2

15

I want to add an "AND" clause to the end of a query builder, the code looks like this:

$orderers = DB::table('address')->where(function($query) use ($term) {
                            $query->where('id', 'LIKE', '%' . $term . '%')
                                    ->or_where('name', 'LIKE', '%' . $term . '%')
                                    ->or_where('status', 'LIKE', '%' . $term . '%')
                                    ->and_clause_goes_here('is_orderer', '=', '1');
                        })->paginate($per_page);

But searching for a AND clause in Laravel I couldn't find any of equivalent. Could you help me with this problem?

Archaeopteryx answered 8/3, 2013 at 2:53 Comment(0)
S
33

JCS solution may still yield some unexpected results due to the order of operations. You should group all the OR's together as you would in SQL, explicitly defining the logic. It also makes it easier to understand for the next time you ( or to another team member ), when they read the code.

SELECT * FROM foo WHERE a = 'a' 
AND (
    WHERE b = 'b'
    OR WHERE c = 'c'
)
AND WHERE d = 'd'


Foo::where( 'a', '=', 'a' )
    ->where( function ( $query )
    {
        $query->where( 'b', '=', 'b' )
            ->or_where( 'c', '=', 'c' );
    })
    ->where( 'd', '=', 'd' )
    ->get();
Semivowel answered 8/3, 2013 at 19:10 Comment(1)
Thanks a lot. and I think it must be orWhere not or_where. It caused an error in laravel 5.5.Overexcite
K
16

simply another where clause will do, AND will be use

$orderers = DB::table('address')->where(function($query) use ($term) {
                            $query->where('id', 'LIKE', '%' . $term . '%')
                                    ->where('is_orderer', '=', '1');
                                    ->or_where('name', 'LIKE', '%' . $term . '%')
                                    ->or_where('status', 'LIKE', '%' . $term . '%')
                        })->paginate($per_page);
Kesselring answered 8/3, 2013 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.