php - 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;
});
模型和数据库架构:
解决方案
您可以使用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();
推荐阅读
- node.js - 如何让 babelify 10 以浏览器为目标
- rust - StructOpt:如何在 clap::arg 属性方法中使用子命令枚举的字段?
- javascript - 2017 年 3 月 12 日奇怪的 Date() 小时增量
- html - 垂直对齐如何改变文本出现的位置?
- octave - 以八度计算逆
- java - 如何从图库中选择图像并存储到 SqlLite 数据库中
- powershell - 在 PowerShell 中使用 Microsoft Graph API 获取 Planner 任务
- laravel - 拉拉维尔。如何获取数据库通知的ID?
- angular - Angular JWT 刷新令牌
- sql - 使用 SQL 获取当前季度的季度环比增长