简体   繁体   English

如何在laravel中建立雄辩的关系?

[英]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. 它一直工作到Auth::user()->group但没有进一步的链接。 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. 但是,如果您基本上想要将结构跳到某个级别,并获得与用户相关的所有成员,则可以使用hasManyThrough关系,因为用户通过组拥有许多成员。

// 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. Laravel不使用查询来访问用户的组,然后再进行另一个查询来访问该组的成员,而是使用带有连接的单个查询来获取成员。

Take a look at the hasManyThrough relationship here 看看这里的hasManyThrough关系

试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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