我有一个操作控制器:
public function getCities(): JsonResponse
{
return response()->json([City::all()], 200);
}
实体城市与国家有关系。
如何为结果 City::all() 中的每个项目添加 country.id?
答案 0 :(得分:0)
您应该查看文档:{{3}}
最好的方法是使用预先加载,使用:
City::with('country')->get();
然后,您可以像这样访问国家/地区 ID:
$city->country->id;
答案 1 :(得分:0)
Laravel 具有创建虚拟属性的惊人功能。为此,将这些行添加到您的城市模型中:
NOTIFICATION: I assume you have and CountryCity model
public $appends = ['country_id'];
public function getCountryIdAttribute()
{
$country = CountryCity::where('city_id',$this->id)
if($country){
return $country->id;
}
return null;
}