laravellaravel-11

How to eager load with query join?


I have a code like this:

    $projects = Project::query()
        ->select('projects.*')
        ->join('tasks', 'projects.id', '=', 'tasks.project_id')
        ->groupBy('projects.id')

So it is a simple join. I want to use eager load on it. I tried

    $projects = Project::with('tasks')->query()
        ->select('projects.*')
        ->join('tasks', 'projects.id', '=', 'tasks.project_id')
        ->groupBy('projects.id')

But it is not the right syntax.

I checked the documentation too, no success.

How to eager load when it is a custom query with join?


Solution

  • Try this and let me know.

    $projects = Project::with('tasks')
        ->select('projects.*')
        ->join('tasks', 'projects.id', '=', 'tasks.project_id')
        ->groupBy('projects.id')
        ->get();