laravel eloquent Filter relations Model values with Base Model id

77 Views Asked by At
$subTasks = SubTask::with(['task']) 
    ->with(['users.subTaskInfos' => function ($q) {
        $q->orderBy('created_at', 'desc');
        $q->where('sub_task_id', '=', ?);
    }])
    ->where('active', 1)
    ->get();

I want to pass Base Model SubTask id in question mark section to filter out relations data and relation collection of data. Can anyone help?

1

There are 1 best solutions below

0
On

One way to achieve what you are attempting is to lazy eager load users.subTaskInfos - keeping the number of queries the same

$subtasks = SubTask::with(['task'])->where('active', 1)->get();

$subtasks->load(['users.subTaskInfos' => function($q) use($subtasks) {
    $q->whereIn('sub_task_id', $subtasks->pluck('id')
        ->orderByDesc('created_at');
});