【问题标题】:Return parent Model column in Laravel在 Laravel 中返​​回父模型列
【发布时间】:2017-05-02 13:21:57
【问题描述】:

我有一张桌子

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

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

【问题讨论】:

  • 如果您对获取您的城市感兴趣,为什么要使用 Country 模型进行主要查询?像City::whereHas('country', function($query){ $query->find(request()->option); })->get(); 这样获取不是更有意义吗?
  • @CarterFort 返回此错误 Column not found: 1054 Unknown column 'cities.country_id' in 'where Clause' (SQL: select * from countries where cities.country_id = @ 987654329@.idcountries.id = 327 限制 1)
  • 您是否在 Cities 迁移中添加了该列?您可以发布您的城市/国家表的迁移代码吗?

标签: php json laravel laravel-5 eloquent


【解决方案1】:

要在使用 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);

【讨论】:

    【解决方案2】:

    试试这个,

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 这正是我的建议。但是您确实需要确保您的数据库列是正确的,这听起来可能是 Adnan 尚未完成的。尽管有时使用此类查询,我会收到与不明确的 id 列相关的 DB 错误,在这种情况下,我必须更改 where 子句以查找 countries.id 而不仅仅是 id
      【解决方案4】:

      你可以这样得到它:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-27
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 2017-11-23
        • 1970-01-01
        • 2015-04-18
        • 2019-05-12
        相关资源
        最近更新 更多