嗨,我有一個表返回父模型cloumn在Laravel
countries
id , country_prefix
cities
city_id, city_name, country_id, city_prefix ,consumer_rates
這裏是我的模型
class Country extends Model
{
public function cities()
{
return $this->hasMany('App\City', 'country_id', 'id');
}
}
這裏是城市模型
class City extends Model
{
protected $primaryKey = 'city_id';
public function country(){
return $this->belongsTo('\App\Country','country_id','id');
}
}
在我的控制器
$cities = Country::find($request->option)
->cities()
->select(['city_id', 'city_name', 'consumer_rates', 'city_prefix'])
->get();
return response()->json($cities);
我需要父模型列在我的
city_id,CITY_NAME,consumer_rates,country_prefix和city_prefix
反應是有一個乾淨的方式來實現這一目標?
如果您有興趣獲取您的城市,爲什麼要使用您的國家/地區模型來執行主要查詢?如果像'City :: whereHas'('country',function($ query){$ query-> find(request() - > option)那樣獲取它會更有意義;}) - > get();'? –
@CarterFort它返回這個錯誤列未找到:1054在'where子句'中的未知列'cities.country_id'(SQL:select * from'countries' where'cities'.'country_id' ='countries'.'id' and 'countries'.'id' = 327限制1) –
您是否在城市遷移中添加了該列?您可以發佈您的城市/國家/地區表格的遷移代碼嗎? –