Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query builder with AND in query

Tags:

php

laravel-3

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?

like image 827
Khanh Tran Avatar asked Mar 08 '13 02:03

Khanh Tran


1 Answers

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();
like image 126
Collin James Avatar answered Oct 16 '22 03:10

Collin James