2016-03-07 149 views
0

我有3種型號:Laravel關係遞歸

市:

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->城市 - >經度,但是當我調用$ cityTranslation->城市 - >國家 - >碼它給了我一個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) 

哪有我做遞歸關係?

+0

你爲什麼在城市和國家之間有一對多?一個城市可以有多個國家? oO它試圖找到city_id在國家,因爲那... – naneri

回答

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

} 

因爲國家可以有很多城市,每個城市都必須屬於一個國家

+0

感謝oseintow,它的工作原理是我希望的,但如果我去城市形式我得到一個錯誤,不幸的是我不知道如何找到我們的問題在哪裏:BadMethodCallException in C:\ xampp \ htdocs \ laravel \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Query \ Builder.php第2161行:調用未定義方法Illuminate \ Database \ Query \ Builder :: city() –

+0

i發現了這個問題。其實只有城市模型中的country()方法屬於To的變化已經足夠了:) –

+0

這很好,你已經發現問題了 – oseintow