0

我得到了一个与州有关的模型城市,因此与国家有关。

当调用与城市相关的模型时,得到了城市但状态返回 null。

我的查询

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

我的模范城市

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

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

1 回答 1

1

使用封闭方法应该可以...

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

向下滚动到以下链接中的“约束急切负载”以查看使用中的封闭方法 https://tower.la.utexas.edu/index.php/docs/database/eloquent#eager

于 2013-07-17T16:01:52.483 回答