简体   繁体   中英

whereIn query not working laravel

Could you help what's the problem with my query. In the second variable, I can't simply output the thing in my blade it using whereIn method. I'm supposed to add another where in the $filterrecord variable, but upon checking, it's not even going through.

Controller

$querys 
    = RecordHistory::select(DB::raw('profile_id, max(effective_date) as date, membership_type'))
        ->groupBy('profile_id')         
        ->orderBy('date', 'desc')
        ->get();

$filterrecord
    = RecordHistory::select('profile_id', 'membership_type')
    ->whereIn('profile_id', $querys)        
    ->get();

Database query returns collection and whereIn accepts array thus first change the collection to an array, you can use the below code and achieve it

 $filterrecord
        = RecordHistory::select('profile_id', 'membership_type')
        ->whereIn('profile_id', $querys->toArray())        
        ->get();

If you use whereIn in query then you pass multiple ids by comma separated

    $querys 
        = RecordHistory::select(DB::raw('profile_id, max(effective_date) as date, membership_type'))
            ->groupBy('profile_id')         
            ->orderBy('date', 'desc')
            ->get();
    $ids = array(); 
     foreach($querys as $item){
       $ids[]=$item->profile_id;
     }       
    $filterrecord
        = RecordHistory::select('profile_id', 'membership_type')
        ->whereIn('profile_id', $ids)        
        ->get();

Parameter 2th of whereIn is array.But your variable "$querys" is a collection object.convert this to array of list profile_id.

$ids = array();
foreach($querys as $item){
  $ids[]=$item->profile_id;
}

or

$ids = array(); 
foreach($querys as $item){
  $ids[]=$item['profile_id'];
}

and use it like:

->whereIn('profile_id', $ids)

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