简体   繁体   中英

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');
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM