Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

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.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

thplat thplat Joined 6 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.