【问题标题】:Concat two columns With laravel eloquent用 laravel eloquent 连接两列
【发布时间】:2019-10-24 18:05:27
【问题描述】:

我有 3 张桌子,1.国家 2.州 3.citites

COUNTRIES 包含 id、name 列。

STATES 包含 id、name、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引用他们各自的国家。喜欢:英国-伦敦

【问题讨论】:

    标签: laravel eloquent concat


    【解决方案1】:

    一种方法是使用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);
    

    【讨论】:

    • 如果我想将每个城市与他们的国家联系起来怎么办。喜欢:英国-伦敦、美国-纽约、...
    • @weaver 你可以急切地用城市加载州和国家,然后再次使用地图。
    猜你喜欢
    • 2014-10-18
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2018-11-06
    • 2019-06-28
    • 2017-03-11
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多