Martzy
Martzy

Reputation: 85

Eagerload 3 models or access between them

I have 3 models, Subforum, Topic and post. Is it possible to Eagerload all 3?

class Subforum extends Model
{
    public function topics()
    {
        return $this->hasMany('App\Topic')->orderBy('sticky', 'desc')->latest("updated_at");
    }
}

class Topic extends Model
{

    public function subforum()
    {
        return $this->belongsTo('App\Subforum');
    }

    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

class Post extends Model
{
    public function topic()
    {
        return $this->belongsTo('App\Topic');
    }
}

Is there any way to do something in the likes of

Subforum::with('topics')->with('posts')->limit(1)->get();

Or how to find what Subforum is Post a part of, through Topic, like

$post->topic()->subforum()

or

$post->subforum()

Upvotes: 0

Views: 17

Answers (1)

lagbox
lagbox

Reputation: 50561

Sure, its called Nested Eager Loading:

Subforum::with('topics.posts')->first();

If you have a Post instance already you can walk the relationship to the Subforum, assuming all these relationships exist in the database:

$post->topic->subform;

Laravel 8.x Docs - Eloquent - Relationships - Eager Loading - Nested Eager Loading

Upvotes: 1

Related Questions