Laravel雄辩的关系获取记录达到第三级关系

时间:2016-10-02 06:31:07

标签: php laravel eloquent

我的users表与vendordetails表有一个hasOne关系。

class User extends Authenticatable
{
    public function vendor_details() {
        return $this->hasOne('App\Vendordetail');
    }
}

另一方面,vendordetails表包含country_id,state_id和city_id,并且具有belongsTo与Country,State和City模型的关系。

Vendordetail.php模型是: -

class Vendordetail extends Model
{
    public $timestamps = false;

    public function this_country(){
        return $this->belongsTo('App\Country', 'country_id');
    }

    public function this_state(){
        return $this->belongsTo('App\Country', 'state_id');
    }

    public function this_city(){
        return $this->belongsTo('App\Country', 'city_id');
    }

}

如果我在用户表上查询,如何获取国家,州和城市的记录。

$user = User::with('vendor_details')->first();

在此查询中,它只查找vendordetails表的结果,我还想要国家,州和城市。

由于

1 个答案:

答案 0 :(得分:4)

访问嵌套关系

$user = User::with(['vendor_details.this_state','vendor_details.this_country','vendor_details.this_city'])->first();

相关问题