在laravel中基于外键分组

时间:2020-04-27 08:30:33

标签: php laravel laravel-query-builder

我在数据库中有以下行 this

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

[
 ...,
 "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;
    });

模型和数据库模式:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用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();