Laravel multiple relationship eager loading with select columns on laravel 9 #45633
-
Description:the tasks relationship returns empty collection, I want to select specific fields on tasks table. DraggableStatus::with(['tasks' => function ($query) use ($project) {
return $query
->with('user:id,avatar')
->select(['id', 'name', 'project_id', 'user_id', 'due_date'])
->where('project_id', $project->id)
->orderBy('due_date');
}])->get(); removing DraggableStatus::with(['tasks' => function ($query) use ($project) {
return $query
->with('user:id,avatar')
->where('project_id', $project->id)
->orderBy('due_date');
}])->get(); Steps To Reproduce:
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
Try this: DraggableStatus::with(['tasks' => function ($query) use ($project) {
return $query
->with('user:id,avatar')
->where('project_id', $project->id)
->orderBy('due_date');
}])->get(['id', 'name', 'project_id', 'user_id', 'due_date']); |
Beta Was this translation helpful? Give feedback.
-
@Ifriqiya |
Beta Was this translation helpful? Give feedback.
-
Can you share both of migration files and relational model methods? |
Beta Was this translation helpful? Give feedback.
-
Are you trying to load DraggableStatus with tasks and user relationship? This what I'll do: DraggableStatus::with(['tasks:id,name,project_id,user_id,due_date', 'user:id,avatar'])
->where('tasks', function ($query) use ($project) {
$query->where('id', $project->id);
})
->orderBy('due_date')
->get(); |
Beta Was this translation helpful? Give feedback.
-
DraggableStatus::with(['tasks' => function ($query) use ($project) {
return $query
->with('user:id,avatar')
->select(['id', 'name', 'project_id', 'user_id', 'due_date', 'draggable_status_id'])
->where('project_id', $project->id)
->orderBy('due_date');
}])->get(); When you select some column into with method, you need to put Foreign Key and Primary Key as well. |
Beta Was this translation helpful? Give feedback.
When you select some column into with method, you need to put Foreign Key and Primary Key as well.