简体   繁体   中英

How to chain eloquent relations in laravel?

So far I was extracting the relation objects as arrays and then doing something like:

App\Model::find($id)

But however is there a way to do something like:

Auth::user()->group()->members()

It works until Auth::user()->group but no further chaining. Please help if you've done something. Or I'm just newbie.

You could use eager loading to load the user's group and then load all of the members of that group.

$user = User::with(['group', 'group.members'])->find(1);

// OR if you already have a user object (Like when using the Auth facade)
$user = Auth::user()->load(['group', 'group.members']);

foreach ($user->group->members as $member) {
    // Do something with a member
}

However, if you essentially want to jump down the structure a level, and get all the members related to a user, you could use the hasManyThrough relationship, in that a user has many members, through a group.

// In your User model
public function members()
{
    return $this->hasManyThrough(Member::class, Group::class);
}

That way you can simply access the members directly through the user:

$members = Auth::user()->members;

Instead of doing a query to access the user's group and then doing another query to access that group's members, Laravel would use a single query with a join to get you the members.

Take a look at the hasManyThrough relationship here

试试这个

Auth::user()->group->members

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM