3

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

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I could swear I tried that option but apparently I didn't! Is it possible to eager load a related model where the company has many of them rather than just one?
Yes, if the relationship is set properly it will return a Collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.