用 laravel eloquent 连接两列

Concat two columns With laravel eloquent

我有 3 个表,1. 国家 2. 州 3.citites

COUNTRIES 包含 id、name 列。

STATES 包含 ID、名称、country_id 列。

CITIES 包含 id, name, state_id.

我正在访问具有 hasManyThrough() 关系的城市。

关系:

public function cities()
{
   return $this->hasManyThrough('App\Models\City','App\Models\State');
}

我如何获取 citeis:

$countryObj = Country::where('name','like',$country.'%')->first();
$cities =  $countryObj->cities->pluck('name');
return response()->json(['cities'=>$cities],200);

我想concat引用他们各自的国家。喜欢:英国-伦敦

一种方法是使用 map。您可以将 $countryObj 传递给它,然后简单地将字符串连接在一起:

$countryObj = Country::where('name', 'like', $country . '%')->first();

$cities = $countryObj->cities->map(function ($city) use ($countryObj) {
    return $countryObj->name . '-' . $city->name;
});

return response()->json(['cities' => $cities], 200);