【发布时间】: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
countrieswherecities.country_id= @ 987654329@.id和countries.id= 327 限制 1) -
您是否在 Cities 迁移中添加了该列?您可以发布您的城市/国家表的迁移代码吗?
标签: php json laravel laravel-5 eloquent