I have the following models set up in Laravel 5 (everything is namespaced into App\Models
, but I've removed that for readability) :
class Client extends Model {
public function templates() { return $this->hasMany('Template'); }
public function documents() { return $this->hasManyThrough('Template', 'Document'); }
public function users() { return $this->hasMany('User'); }
}
class Template extends Model {
public function client() { return $this->belongsTo('Client'); }
public function documents() { return $this->hasMany('Document'); }
}
class Document extends Model {
public function template() { return $this->belongsTo('Template'); }
}
In a controller, I have the current user:
$user = \Auth::user();
$client = $user->client;
I want to show a list of
- the templates for a client
- the documents for a client, separately, not grouped by template
It seems easy enough; I already have both of the relations needed. The question is, if I lazy eager load templates
and documents
onto $client
, do I still need to eager load templates.documents
(hasManyThrough) or is Laravel smart enough to realise?
$client->load( 'templates', 'documents' );
// or...
$client->load( 'templates', 'templates.documents' );
// or...
$client->load( 'templates', 'documents', 'templates.documents' );