php - 如何在 Laravel 中对多对多关系集合的总价格求和
问题描述
这是 withCount 的集合
Illuminate\Database\Eloquent\Collection {#12203
all: [
App\Product {#12171
id: 1,
description: "Test 1",
price: 600.0,
applications_count: 314,
},
App\Product {#12195
id: 2,
description: "Test 2",
price: 1000.0,
applications_count: 1129,
},
App\Product {#12201
id: 3,
description: "Test 3",
price: 1500.0,
applications_count: 6,
},
试过了
$products = Product::withCount('applications')->get();
return $this->result(
$products->flatMap(function ($product) {
return [
$product->price => $product->applications_count
];
})->toArray()
);
我需要找到集合的总数,我猜基本上应该是 price * application_count。请给我一个想法。
解决方案
遍历每个$product
in$products
并计算price * application_count
然后将其求和到一个变量中并返回它:
$products = Product::withCount('applications')->get();
$total_price = 0;
foreach ($products as $product){
$total_price += $product['price'] * $product['applications_count'];
}
return $total_price;
推荐阅读
- android - 二进制 XML 文件第 17 行:膨胀类 com.google.android.material.textfield.TextInputLayout 时出错
- c# - 如何使用参数从命令行运行 Xunit 测试
- r - 使用序号在 data.frame 列中继续数字系列
- python - Django 部署后的服务器错误 (500)
- windows - C/C++ / Windows 10:如何枚举像 diskpart 这样的卷?
- maven - 将 Maven 插件用于 Sonatype OSS 索引时出现“未绑定 org.sonatype.ossindex.maven.common.ComponentReportAssistant 的实现”错误
- javascript - 从服务器获取精确的 ping(毫秒)
- python - 根据条件获取最小日期和最大日期之间的时间差
- ios - 仅当用户访问我的应用程序中的特定网站时,我如何才能显示警报?
- bash - 在 git diff 中查找带有文件名和行号的 TODO