尝试构建 Laravel 项目订单相关信息的报告结果。但很难找到针对特定数据结构的解决方案。
我的要求:
// Date Ranges
$fromDate = $this->request->fromDate;
$toDate = $this->request->toDate;
所以结果应该在一个日期范围内。
我的订单表:
order_id order_addresses grand_total
------------------------------------------
1 JSON DATA 3,000.00
2 JSON DATA 2,000.00
3 JSON DATA 1,500.00
所以我的 JSON 数据
看起来像这样:
{
"delivery_address":{
"House":"Offline House",
"Street":"Offline Road",
"Area":"Offline Area",
"PostCode":"1230",
"City":"City1",
"Country":"Country1",
"ContactPerson":"Offline User",
"ContactNumber":"01XXXXXXXX"
}
}
我只想得到如下响应:
{
"orders": 3, // How many orders are there in that particular city
"totals": "5,500.00", // Total how much the cost of orders in that city
"groupby": "City1",
},
{
"orders": 5,
"totals": "7,500.00",
"groupby": "City2",
},
...,
...
我正在寻找一种使用 Laravel 中的查询生成器和 MySQL 的解决方案。
这是一个现有的项目,所以我无法真正改变它的构建方式。因此,关于如何从与订单例份以及总数等相关的 JSON 数据中提取城市的任何建议。 我只需要 order_ids 我认为城市明智,然后我可以构建我的结果无论如何我喜欢实现最终结果。
如果这里有任何疑问,请告诉我,以便我能够澄清。
提前致谢!
最佳答案
我建议使用 Laravel Collection 函数对获取的数据进行分组。
订单模型
class Order extends Model {
// This will cast data to native types.
// so order_address json string to array
protected $casts = [
'order_addresses' => 'array',
];
}
Controller 功能
// Fetch orders from the database as you usually do
// without considering about grouping.
// with your conditions.
// I will simply use all() for example.
$orders = Order::all();
// First group by city
// Then map to get the result you want.
$groupedOrders = $orders->groupBy(function($order) {
// since we added it to the casts array in the model
// laravel will automatically cast json string to an array.
// So now order_address is an array.
return $order->order_addresses['City'];
})
->map(function($groupedOrders, $groupName) {
return [
'orders' => $groupedOrders->count(),
'totals' => $groupedOrders->sum('grand_total'),
'groupby' => $groupName,
];
});
关于mysql - 如何使用 Laravel、MySql、JSON 按不同城市对订单进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57945090/