Группировка по внешнему ключу в laravel - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть следующие строки в базе данных 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 голосов
/ 27 апреля 2020

Вы можете использовать отношение belongsToMany() (https://laravel.com/docs/7.x/eloquent-relationships#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();
...