首页 > 解决方案 > 如何在 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。请给我一个想法。

标签: phplaravel

解决方案


遍历每个$productin$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;

推荐阅读