Jun 1, 2017
0
Level 4
Get all projects with assigned / not_assigned projects
Hi,
I have three tables: users, projects, and project_user (pivot). I need to display all the projects with a Assigned / Not Assigned label on them to a user.
For a single project page, I could do it by
$is_already_assigned = $project->assigned_artists()
->wherePivot('user_id', Auth::user()->id)
->first();
if( $is_already_assigned ){
// do something
}
However, for all the projects, I'm doing this
$projects = Project::with('assigned_artists')->paginate(12);
foreach( $projects as $project ){
// Check the pivot table to see the current user is assigned to this project
// $project->is_assigned = true;
}
Running 12 extra queries per page loading! it looks pretty bad already :(
Is there a cleaner way to add an additional attribute to the result depending on if the current user exists in a pivot table?
Thanks,
Please or to participate in this conversation.