2016-12-16 23 views
2

嗨,我有一個表返回父模型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

反應是有一個乾淨的方式來實現這一目標?

+0

如果您有興趣獲取您的城市,爲什麼要使用您的國家/地區模型來執行主要查詢?如果像'City :: whereHas'('country',function($ query){$ query-> find(request() - > option)那樣獲取它會更有意義;}) - > get();'? –

+0

@CarterFort它返回這個錯誤列未找到:1054在'where子句'中的未知列'cities.country_id'(SQL:select * from'countries' where'cities'.'country_id' ='countries'.'id' and 'countries'.'id' = 327限制1) –

+0

您是否在城市遷移中添加了該列?您可以發佈您的城市/國家/地區表格的遷移代碼嗎? –

回答

0

你可以得到這樣的:

$response = DB::table('country') 
    ->select('cities.city_id', 'cities.city_name','cities.consumer_rate','country.country_prefix','cities.city_prefix') 
    ->join('cities', 'country.id', '=', 'cities.country_id') 
    ->get(); 
1

您可以使用關係查詢父模型爲:

City::whereHas('country', function($q) { 
     $q->where('id', request()->option); 
    }) 
    ->with('country') 
    ->get(); 
+0

這正是我所建議的。但是你確實需要確保你的數據庫列是正確的,這聽起來好像Adnan還沒有完成。儘管有時使用這種查詢,我得到了一個與模糊的「id」列相關的數據庫錯誤,在這種情況下,我必須更改我的where子句以查找「countries.id」而不是「id」。 –

0

試試這個,

$country = Country::with('cities')->find($request->option); 
$cities = $country->cities; 
0

要安裝它在使用find()方法後使用load()方法延遲加載該關聯離子:

$cities = Country::find($request->option) 
    ->load(['cities' => function($query) { 
     return $query->select(['city_id', 'city_name', 'consumer_rates', 'city_prefix']); 
    }]); 

return response()->json($cities); 
相關問題