laravel 如何在laravel中链接雄辩的关系?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40057334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to chain eloquent relations in laravel?
提问by Leap Hawk
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.
它工作直到Auth::user()->group
但没有进一步的链接。如果你做了什么,请帮忙。或者我只是新手。
回答by Jonathon
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 关系
回答by Vikash
Try this
尝试这个
Auth::user()->group->members