如何在laravel中建立雄辩的关系? [英] How to chain eloquent relations in laravel?

查看:36
本文介绍了如何在laravel中建立雄辩的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我将关系对象提取为数组,然后执行以下操作:

  App \ Model :: find($ id) 

但是有一种方法可以做到:

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

它可以一直工作到 Auth :: user()-> group ,但不再进行链接.如果您已完成操作,请提供帮助.或者我只是新手.

解决方案

您可以使用紧急加载加载用户组,然后加载该组的所有成员.

  $ user = User :: with([['group','group.members'])-> find(1);//或者,如果您已经有一个用户对象(例如使用Auth Facade时的对象)$ user = Auth :: user()-> load(['group','group.members']);foreach($ user-> group->成员为$ member){//与成员一起做某事} 

但是,如果您本质上想跳到一个结构层次并获取与用户相关的所有成员,则可以使用 hasManyThrough 关系,因为用户通过一个小组.

 //在您的用户模型中公共职能成员{返回$ this-> hasManyThrough(Member :: class,Group :: class);} 

这样,您可以直接通过用户直接访问成员:

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

Laravel不会执行查询来访问用户组的查询,而是执行另一个查询来访问该组的成员,而是使用带有联接的单个查询来获取您的成员.

看看hasManyThrough关系此处

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

这篇关于如何在laravel中建立雄辩的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆