在Laravel中返回父模型列

时间:2016-12-16 17:31:35

标签: php json laravel laravel-5 eloquent

我有一张表

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

在我的控制器中

{{1}}

我的回复

中需要父模型列

city_id,city_name,consumer_rates,country_prefix和city_prefix

有没有一种干净的方法来实现这一目标?

4 个答案:

答案 0 :(得分:1)

您可以使用您的关系查询父模型:

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

答案 1 :(得分:1)

试试这个,

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

答案 2 :(得分: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();

答案 3 :(得分: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);