简体   繁体   中英

Find child model hasMany relation in laravel eloquent

Here is model structure of my Laravel 5.3 project,


  • User.php (Model)

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)

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; 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.

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