16

How do I go about using multiple Eloquent With()'s?

PortalPlaylistElement Model

class PortalPlaylistElement extends Model
{
    public $primaryKey = 'code';
    public $incrementing = false;
    public $timestamps = false;

    public function AirtimePlaylists()
    {
        return $this->hasOne('App\AirtimePlaylist','id','playlist_id');
    }
}

AirtimePlaylistContent Model

class AirtimePlaylistContent extends Model
{
    protected $table = 'cc_playlistcontents';
}

AirtimePlaylistModel

class AirtimePlaylist extends Model
{
    protected $table = 'cc_playlist';

    public function PortalPlaylistElements()
    {
        return $this->belongsTo('App\PortalPlaylistElement','playlist_id');
    }

    public function AirtimePlaylistContents()
    {
        return $this->hasMany('App\AirtimePlaylistContent','playlist_id');
    }
}

I have no problems with:

AirtimePlaylist::with('AirtimePlaylistContents')->get());

or

PortalPlaylistElement::with('AirtimePlaylists')->get();

But I'd like to get all AirtimePlaylistContents, in an AirtimePlaylist that belongs to a PortalPlaylistElement.

In essence, (Pseudo code)

PortalPlaylistElement::with('AirtimePlaylists')::with('AirtimePlaylistContents')->get();

3 Answers 3

39

You need Nested Eager Looading

PortalPlaylistElement::with('AirtimePlaylists.AirtimePlaylistContents')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on - Have managed to further nest the additional models aswell. Thanks so much - I'll have a read up on them now I know what to look for!
12

nested relations

 with('relation1.relation2.relation3')->get(); // relation1 has relation2 relation2 has relation 3

not nested relations

 with('relation1','relation2','relation3')->get(); // you model has all relations

2 Comments

but 'where clauses' inside 'with' seem to be ignored.. Anyone who knows how to deal with those cases?
can you show what you already tried? so i can get a better idea on what you are trying to achieve!
5

I would like to add this if someone needed it

 with(['relation1.relation2-1','relation1.relation2-2'])->get(); // relation1 has relation2-1 and relation1 also has relation2-2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.