首页 > 解决方案 > 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},
]

标签: phplaravellaravel-5query-builder

解决方案


订单模式

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]},
]

推荐阅读