BlaShadow
BlaShadow

Reputation: 11693

Eager loading laravel 3 deep relationship

I got a model City related with State and so with Country.

When call a model realted with city a got the city but state return null.

my query

Agent::with(array('city','city.state'))->find($id);

my model city

class City extends Eloquent
{
    public static $table = 'city';

    public function State()
    {
        return $this->belongs_to('State','state_id');
    }
}

Upvotes: 0

Views: 1144

Answers (1)

Dax Borges
Dax Borges

Reputation: 21

Using an enclosure method should work...

// Like this...
Agent::with(array('city' => function($query){
    $query->with('state'); 
}))->find($id);

// Also, I would keep my model relationship methods lowercase
class City extends Eloquent
{
    public static $table = 'city';

    //public function State()
    public function state() // like this
    {
         return $this->belongs_to('State','state_id');
    }
}

Scroll down to "Constraining Eager Loads" at the below link to see enclosure methods in use https://tower.la.utexas.edu/index.php/docs/database/eloquent#eager

Upvotes: 1

Related Questions