The easiest way to fetch those far related models is this:
$user = User::with('groups.projects')->find($someUserId);
// then:
$projects = new Illuminate\Database\Eloquent\Collection;
$user->groups->each( function ($group) use (&$projects) {
$projects = $projects->merge($group->projects);
});
Above code will execute 2 queries: first to fetch the groups and another to fetch the projects. Then you work with the collections.
You can also do this:
// User model
protected $projects;
public function getProjectsAttribute()
{
if ($this->projects) return $this->projects;
$groupsKeys = $this->groups->modelKeys();
$keyName = with(new Group)->getQualifiedKeyName();
return $this->projects = Project::whereHas('group', function ($q) use ($groupsKeys, $keyName) {
$q->whereIn($keyName, $userIds);
})->get();
}
// then you can access it just like that:
$user->projects;
This will execute 2 queries as well and assign projects to the user's property 2nd example was wrapped in an accessor code to ease working with it, but of course you can use 1st code within that accessor instead.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community