简体   繁体   中英

Laravel query builder with AND in query

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?

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();

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM