php - Laravel:结合基于公共领域的转换数据
问题描述
我正在从我的控制器中的查询中转换一些数据并将其返回到前端。我得到了一系列自定义转换的“订单”,其中包含我需要的信息。我将每隔几秒钟调用一次这个端点。我正在尝试查看是否有一种方法可以组合total
所有具有相同的订单customer_id
控制器
$orders = Order.where("type", "=", "valid")->get();
foreach ($orders as $order) {
$ordersArray[] = [
'order_id' => $order->id,
'customer_name' => $order->customer_id),
'customer_id' => $order->customer_id,
'total' => $order->total,
];
}
return [
'paidOrders' => $ordersArray,
];
返回到前端的示例
[
{order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
{order_id: 315, customer_name: "Barry", customer_id: 82, total: 217},
{order_id: 316, customer_name: "Barry", customer_id: 82, total: 217},
{order_id: 317, customer_name: "Barry", customer_id: 82, total: 147},
]
我想要返回的示例 - 只需合并同一客户的总数
[
{order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
{order_id: ?, customer_name: "Barry", customer_id: 82, total: 581},
]
解决方案
订单模式
public function customer(){
return $this->belongsTo(App\Customer, 'customer_id', 'id');
}
客户模型
public function orders(){
return $this->hasMany(App\Order, 'customer_id', 'id');
}
控制器
$orders = Order::with('customer')->where('type', 'valid')->get();
$customers = [];
foreach($orders as $order){
if(!isset($customers[$order->customer_id])){
$customers[$order->customer_id]['customer_name'] = $order->customer->name;
$customers[$order->customer_id]['customer_id'] = $order->customer_id;
$customers[$order->customer_id]['total'] = $order->total;
}
else{
$customers[$order->customer_id]['total'] += $order->total;
}
$customers[$order->customer_id]['orders'][] = $order->id;
}
$result = array_values($customers);
输出格式
[
{ customer_name: "Martin", customer_id: 71, total: 66, orders: [314]},
{ customer_name: "Martin", customer_id: 71, total: 581, orders: [315, 316, 317]},
]
推荐阅读
- java - Apache HTTP 客户端 - 带有格式错误的质询的 401 错误:乱序 NTLM 响应消息警告
- javascript - 如何使回调返回未在其范围内定义的变量?
- postgresql - 如何使用 metricbeat 从 postgres 中检索语句指标
- google-chrome - 如何以非自动安装的方式提供 crx 文件
- jquery - 基于 Jquery 行索引的选择列表填充
- python - 视差图数组中的点云
- github - 如何在 Ansible 剧本中从 github 检索和使用 tar.gz.asc?使用给定的 gpg 密钥?
- openstack - 60 秒后未找到按主机名注册的服务 - Openstack/devstack 部署失败
- javascript - 如何在单页中使用 php 从 while 循环中生成多个阅读更多按钮?
- android - 使用recycleView时如何在滑动时删除文本