php - Laravel whereIn with a where clause on each array item -


say have user object (which belongstomany groups) , i'm doing wherein array of respected ids so:

wherein('user_id', $group->users->modelkeys()) 

i need to, however, set condition pull data each array item based on condition of group_user pivot table, "created_at" (which timestamp of when user added group).

so need this:

wherein('user_id', $group->users->modelkeys())->whereraw('visits.created_at > group_user.created_at') 

that doesn't work though because it's not doing whereraw each array item it's doing once query whole. might need nested wherein not sure if that'll solve either. thoughts?

my full query now:

     $ids = $group->users->modelkeys();       return db::table('visits')->wherein('user_id', function($query) use ($ids) {         $query->select('user_id')->from('group_user')->wherein('group_user.user_id', $ids)->whereraw('visits.created_at > group_user.created_at');     })->sum("views"); 

ok got work using nested loops instead:

    $visits = db::table('visits')->wherein('user_id', $group->users->modelkeys())->get();      $sum = 0;      foreach($group->users $user) {          foreach($visits $visit) {              if($visit->user_id == $user->id) {                  if($visit->created_at >= $user->pivot->created_at) {                     $sum += $visit->views;                 }             }         }      }      return $sum; 

would still see if it's possible in single query, no array looping.

have considered using foreach?

$users = wherein('user_id', $group->users->modelkeys());  foreach ($users $user) {   // comparison here } 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -