Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent ORM - Nested with statements

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.

like image 776
LalienX Avatar asked Jun 12 '16 08:06

LalienX


1 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();

like image 179
joruro Avatar answered Oct 19 '22 00:10

joruro