简体   繁体   English

在laravel eloquent中找到子模型有很多关系

[英]Find child model hasMany relation in laravel eloquent

Here is model structure of my Laravel 5.3 project,这是我的 Laravel 5.3 项目的模型结构,


  • User.php (Model) User.php (模型)

it has one invitation method that returns the invitation of a user.它有一种邀请方法可以返回用户的邀请。

public function invitations()
{
    return $this->hasMany( 'App\Invitation', 'invitee_id', 'id' );
}

  • Invitation.php (Model) Invitation.php (模型)

This model has another method that would return the inviter detail of an invitation.这个模型有另一个方法可以返回邀请的邀请者详细信息。

public function inviter()
{
    return $this->hasOne( 'App\User', 'id', 'invited_by' );
}

If i want to retrieve all invitations of current user it works,如果我想检索当前用户的所有邀请,它可以工作,

\Auth::user()->invitations;

But if i try to get the information about the inviter it won't work!但是,如果我尝试获取有关邀请者的信息,它将不起作用! (Question: How to do it?) (问题:怎么做?)

\Auth::user()->invitations->inviter;

Though i can query the inviter from a invitation eloquent object like this,虽然我可以从这样的邀请雄辩对象中查询邀请者,

\App\Invitation::first()->inviter;

But this is not working when i try to access it from the user model -> invitation -> inviter!但是当我尝试从用户模型 -> 邀请 -> 邀请者访问它时,这不起作用! Also can i use eager loading here?我也可以在这里使用预先加载吗?

\Auth::user()->invitations->inviter;

Looking at this, it appears that you're attempting to retrieve the inviter property from a collection of invitations.看看这个,您似乎正在尝试从邀请集合中检索邀请者属性。 The reason Ken's suggestion to use \\App\\Invitation::first()->inviter; Ken 建议使用\\App\\Invitation::first()->inviter; worked is because you are retrieving the inviter of only one invitation (in this instance, the first).工作是因为您只检索一个邀请(在本例中为第一个)的邀请者。 To resolve this, loop through your invites before attempting to retrieve the properties for each one:要解决此问题,请在尝试检索每个邀请的属性之前循环浏览您的邀请:

$invitations = \Auth::user()->invitations;

foreach ($invitations as $invitation) {
    $inviter = $invitation->inviter;
}

There is also an each() method specific to Laravel Collections that will allow you to loop through your object.还有一个特定于 Laravel 集合的 each() 方法,它允许您循环遍历您的对象。

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

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