mercredi 24 août 2016

Laravel 5.2 How to lazy load a relationship onto a many-to-many relationships results

Is it possible to extend a many-to-many relationship between in this case Events and Users with a pivot table of event_user:

// EVENT MODEL

public function invites()
{
    return $this->belongsToMany('App\User', 'event_user')
                ->withPivot('attendance');
}

// USER MODEL

public function invites()
{
    return $this->belongsToMany('App\Event', 'event_user')
                ->withPivot('attendance');
}

That the user results contain their profile as well? So for example using:

// USER MODEL

public function profile()
{
    return $this->hasOne('App\UserProfile');
}

And something like:

$event->invites()->with('profile')->get();

Currently right now $event->invites; provides a list of all the users, but without their associated profiles. So the only way I can see to do this is to re-query the users based on a list of IDs I'd extract from the result collection, seems like it could be easier, but using lazy loading of either user.profile or profile says the method or value is undefined.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire