1 回答
TA贡献1813条经验 获得超2个赞
问题是您要进行很多查询,并且速度不可避免地会很慢。该解决方案应该具有更好的性能,因为您只进行了两次查询。
$orders = orders::with(['orderDetails'])->get();
$now = Carbon::now();
$quantities = [];
foreach($orders as $order) {
$daysOld = $order->date->diffInDays($now);
foreach ($order->orderDetails as $details) {
if (!isset($quantities[$details->SKU])) {
$quantities[$details->SKU]['30'] = 0;
$quantities[$details->SKU]['60'] = 0;
$quantities[$details->SKU]['90'] = 0;
$quantities[$details->SKU]['120'] = 0;
$quantities[$details->SKU]['total'] = 0;
}
if ($daysOld <= 30) {
$quantities[$details->SKU]['30'] += $details->quantity;
}
if ($daysOld <= 60) {
$quantities[$details->SKU]['60'] += $details->quantity;
}
if ($daysOld <= 90) {
$quantities[$details->SKU]['90'] += $details->quantity;
}
if ($daysOld <= 120) {
$quantities[$details->SKU]['120'] += $details->quantity;
}
$quantities[$details->SKU]['total'] += $details->quantity;
}
}
return products::all()->map(function ($product) use ($quantities) {
$product->sales30days = $quantities[$product->asin]['30'];
$product->sales60days = $quantities[$product->asin]['60'];
$product->sales90days = $quantities[$product->asin]['90'];
$product->sales120days = $quantities[$product->asin]['120'];
$product->salesTotal = $quantities[$product->asin]['total'];
return $product;
});
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报