Laravel Eloquent ORM - Nested Statements

So, I am creating an API for the web application being created, and I am trying to save it in the Eloquent ORM. There are parent-child relationships that I continue:

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 create an instance of the SiteLog class using:

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

When I make a GET request with jQuery, I get all the sites and inside them I have an array of objects with all the data for the relevant logs. This is exactly what I wanted. However, I would like to do this even further and get the user to associate the log with.

It looks like this will work:

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

But all in one statement, as if it were one big connection request. However, I'm not sure if the Eloquent ORM covers the test case.

- - - ? SQL-, , .

+4
2

Eloquent :)

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

, , :

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

+6

- :

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

Laravel 5.2 - - - -

:

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

All Articles