如何在雄辩的laravel中以嵌套数组的形式获得总和?

时间:2019-04-22 04:33:05

标签: javascript php laravel vue.js

我如何获得雄辩的laravel中 reviews 数组上 ratings 的所有结果的总和?

我已经尝试过这种方式:

PublicController.php

public function products()
{
    $products = Product::select('id', 'name', 'slug', 'image', 'new', 'offer', 'featured', 'cash_price', 'special_price')
        ->where('status', true)
        ->withCount(['reviews'])
        ->with(['reviews' => function($query){
            $query->select('product_id', 'rating');
            $query->sum('rating'); //<-- dont show anything
        }])
        ->get();
    return response()->json($products, 200);
}

我的结果json输出是:

[
  {
    "id": 1,
    "name": "Peggie Rodriguez",
    "slug": "peggie-rodriguez",
    "image": "https://lorempixel.com/200/200/?43622",
    "new": 1,
    "offer": 1,
    "featured": "Exercitationem eum praesentium soluta placeat. Ut praesentium non dolorem a et libero. Optio corporis est assumenda aut.",
    "cash_price": 80464,
    "special_price": 10598,
    "reviews_count": 3,
    "reviews": [
      {
        "product_id": 1,
        "rating": 1
      },
      {
        "product_id": 1,
        "rating": 2
      },
      {
        "product_id": 1,
        "rating": 5
      }
    ]
  },
]

我的预期输出是所有额定值的总和。

0 个答案:

没有答案