Reputation: 79
I have the following Eloquent query
Task::whereIn('user_id', [5,6,7,8])
->onlyActive()
->with('user')
->get();
which works perfect. The problem is that each user_id
can have multiple Tasks, but i do only want to return one Task of each user_id
.
Any ideas?
Upvotes: 0
Views: 256
Reputation: 606
why not use take()?
->with([
'user' => function($user) {
$user->tasks()->take(1);
}
])
Upvotes: 0
Reputation: 12835
Easiest would be to define a new relationship on User model to get the latest Task - if that works for you
class User extends Model
{
public function tasks()
{
return $this->hasMany(Task::class);
}
public function latestTask()
{
return $this->hasOne(Task::class)->latest();
}
}
Then to query one active Task for each user
User::whereIn('id', [5,6,7,8])
->with(['latestTask' => function($query){
$query->onlyActive();
}])
->get();
Upvotes: 1