Home » Php » php – Laravel Eloquent ORM – Nested with statements

php – Laravel Eloquent ORM – Nested with statements

Posted by: admin July 12, 2020 Leave a comment

Questions:

So I’m creating an API for a web application I’m creating and I’m trying to keep it within the Eloquent ORM. There is a parent-child relationship that I have going on:

User -> Site Logs -> Sites

Site class code:

class Site extends Model {
    public function log() {
        return $this->hasMany('App\SiteLog', 'site_id', 'id');
    }
}

SiteLog class code:

class SiteLog extends Model
{       
    public function site()
    {
        return $this->belongsTo('App\Site', 'site_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

When I instantiate the SiteLog class using:

$sites = Site::with('log')->get();

When I make the GET request with jQuery, I get all of the sites and inside of them I have an array of objects with all of the data for the sites respective logs. Which is exactly what I wanted. However, I wanted to take it a step further and get the user that the log is associated with.

Sort of like how this would work:

SiteLog::with('user')->get();

But all in one statement as if it was one big join query. However, I’m not sure if the Eloquent ORM covers a test case like that.

Has anybody ever accomplished something like this? I can get this done with some pretty hacky practices or just writing a raw SQL query, but I am just wondering if there was a more eloquent way of doing this.

How to&Answers:

Eloquent allows you to do that easily 🙂

https://laravel.com/docs/5.2/eloquent-relationships#eager-loading

If you also need the user related with each log you just have to eager load it like this

$sites = Site::with('log.user')->get();

Answer:

Something like:

Site::with('log.user')->get();

Laravel 5.2 Docs – Eloquent – Relationships – Eager Loading – Nested Eager Loading

You would end up with a structure something like:

Site
    log: [
        SiteLog
            User
        SiteLog
            User
        ...
    ]