0
$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?

Tharaka Dilshan
  • 4,371
  • 3
  • 14
  • 28
ishtiak122
  • 11
  • 2
  • is your sub_task_id a foreign key then you don't have to link laravel will do that for you – bhucho Dec 13 '20 at 20:37
  • 1
    @bhucho I guess the users associated with a SubTask **can** have SubTaskInfos which are not related with the SubTask - maybe I'm wrong – Donkarnash Dec 13 '20 at 20:40

1 Answers1

1

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');
});
Donkarnash
  • 12,433
  • 5
  • 26
  • 37