Reputation: 1577
I am trying to get eager loading working when fetching related models.
public function allCompanies() {
$companies = $this->companies()->active()->get();
$companies->load('Industry');
return $companies;
}
I have this function on the model Industry and I believe this should fetch the companies which are within the current industry, it should also fetch the related industry for the companies (this will be the current record)
This doesn't seem to work as when I iterate over the companies it re-fetches the Industry for each one.
Am I doing something wrong with the $companies->load('Industry');
line?
Thanks
Upvotes: 3
Views: 10692
Reputation: 481
Try:
public function allCompanies() {
$companies = $this->companies()->active()->with('industry')->get();
return $companies;
}
The with() and load() functions are referencing functions within the model not the model itself ie:
class Company extends Eloquent {
public function industry()
{
return $this->belongsTo('Industry');
}
}
class Industry extends Eloquent {
public function companies()
{
return $this->hasMany('Company');
}
}
Please reference http://laravel.com/docs/eloquent#eager-loading
Upvotes: 6