首页 > 解决方案 > laravel中根据外键分组

问题描述

我在数据库中有以下行 这个

需要在响应中获得以下格式:

[
 ...,
 "centers":[
  {
   id:1,
   shifts:[
       {id:2},
       {id:4}
   ]
  }
 ]
]

但我得到的是如下:

 [
 ...,
 "centers":[
  {
   id:1,
   shift_id : 2
  },
  {
   id:1,
   shift_id : 4
  }
 ]
]

这是我试图得到我想要的代码:

    $accountID = 1; 
    // final result is vechiles and it's related data
    $vehicles = Vehicle::where(['account_id'=>$accountID])->get()- 
    >map(function($item,$key) use ($accountID){
        $vehicleID = $item->id;
        // get centers whicr are belongs to for each vehicle
        $item['centers'] = Chv::where([['account_id',$accountID], 
    ['vehicle_id',$vehicleID]])->get();

        return $item;
    });

模型和数据库架构:

在此处输入图像描述

标签: phplaravellaravel-query-builder

解决方案


您可以使用belongsToMany()https://laravel.com/docs/7.x/eloquent-relationships#many-to-many)关系来获得轮班:

模型中心:

public function shifts(){
   return $this->belongsToMany('App\Shift', 'chvs');
}

在您的代码中:

$item['centers'] = Center::with('shifts')
      ->where([['center_id',$center_id],['account_id',$accountID],['vehicle_id',$vehicleID]])
      ->get();

推荐阅读