简体   繁体   中英

How to use two WhereIn with Laravel

I have a simple query, where $clubs and $user_ids are array. I want to use two WhereIn's in the same query.For example $clubs = array(1,2,3) and $user_id = array(25,30,40). And there is an entry in DB as this user_id =25 and corresponding club_id = 1. I want to list, user_id = 25 from the query result.

$query = \DB::table('users_clubs')          
            ->WhereIn('user_id', $user_ids)
            ->WhereIn('club_id',$clubs)
            ->lists('user_id');

This is somehow the code of whereIn in core

public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    $type = $not ? 'NotIn' : 'In';

    // ... irrelevant code omitted ...

    $this->wheres[] = compact('type', 'column', 'values', 'boolean');

    $this->addBinding($values, 'where');

    return $this;
}

It does not seems it is possible directly , but if you can override it in some way , it may be helpful.

Another way is using advance where

DB::table('users_clubs')
            ->Where(function($query)
            {
                foreach( $user_ids as $user_id ){
                    $query->where('user_id', '=', $user_id);
                }

            })
            ->Where(function($query)
            {
                foreach( $clubs as $club){
                    $query->where('club_id', '=', $club);
                }
            })
            ->get();

Not tested it but it seems it may work with some modification .

are you getting any error ? or didn't tried your query ? you can use multiple whereIn() as much as you want. after WhereIn() add get() then lists()

eg try this

$query = \DB::table('users_clubs')          
            ->WhereIn('user_id', $user_ids)
            ->WhereIn('club_id',$clubs)
            ->get()
            ->lists('user_id');

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