Laravel Relationships递归

时间:2016-03-07 20:29:45

标签: php mysql laravel relationship laravel-5.2

我有3个型号:

城市:

protected $fillable = [
    'name', 'latitude', 'longitude', 'code', 'country_id', 'status', 'weather_code',
];

public function translations() {

    return $this->hasMany('App\Models\CityTranslation');

}

public function country() {

    return $this->hasMany('App\Models\Country');

}

CityTranslation

protected $fillable = [
    'name', 'lang', 'city_id',
];

public function city() {
    return $this->hasOne('App\Models\City', 'id', 'city_id');
}

和国家

protected $fillable = [
    'code', 'latitude', 'longitude', 'currency_id', 'timezone', 'dam_date', 'status',
];

public function city() {

    return $this->hasMany('App\Models\City');

}

我的问题是当我浏览我的CityTranslations并显示所选语言的城市名称时,我还想显示有关该城市及其国家的信息。

调用$ cityTranslation-> city->经度没有问题,但是当我调用$ cityTranslation-> city-> country->代码时,它会给我一个MySQL错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'countries.city_id' in 'where clause' (SQL: select * from `countries` where `countries`.`city_id` = 4439 and `countries`.`city_id` is not null) 

如何进行递归关系?

1 个答案:

答案 0 :(得分:0)

尝试

$cityTranslation = \App\CityTranslation::with('city.country')->get();

如果你想获得所有城市翻译及其相关的城市和国家。您可以循环访问并获取国家/地区代码。

如果您只想选择一个城市翻译及其相关项目

$cityTranslation = \App\CityTranslation::with('city.country')->find($id);

更改此项(在您的城市模型中)

public function country() {

    return $this->hasMany('App\Models\Country');

}

public function country() {

    return $this->belongsTo('App\Models\Country');

}

因为国家可以拥有多个城市,每个城市都必须属于一个国家

相关问题