【问题标题】:Adding a Sum in fractal collection meta data在分形集合元数据中添加总和
【发布时间】:2019-12-01 14:40:35
【问题描述】:

如何遍历集合中的所有项目以获取对象中键的总和?

$data = fractal()
            ->collection($items, new ItemTransformer())
            ->paginateWith(new IlluminatePaginatorAdapter($paginator))
            ->addMeta([
                'from' => $from->toDateString(),
                'till' => $till->toDateString(),
            ])
            ->toArray();

在 addMeta() 中,我想包含所有项目的“总和”->价格->价值。

当我这样添加时:

$totalSum = $items->sum(function($item){
    return $item->price->sum('value);
}

    $data = fractal()
                ->collection($items, new ItemTransformer())
                ->paginateWith(new IlluminatePaginatorAdapter($paginator))
                ->addMeta([
                    'from' => $from->toDateString(),
                    'till' => $till->toDateString(),
                    'total_sum' => $totalSum,
                ])
                ->toArray();

它不会遍历集合,而是遍历 items 表中的所有值。

【问题讨论】:

标签: php laravel


【解决方案1】:

也许这会起作用?

$sum = 0;
$totalPrice = $items->price;
foreach($totalPrice as $key=>$value){

if(isset($value->value))   
    $sum += $value->value;
}

echo $sum;

【讨论】:

  • 是的,这是我的第一个方法,但它似乎有点 hacky。我认为必须有一些优雅的方法。
  • @MichaelPloeckinger 或许可以试试 $sum = array_sum((array)$items->price->value);
  • @MichaelPloeckinger 也许有点“hacky”,但绝对不是坏习惯
【解决方案2】:

我目前的做法:

        $seller = $this->sellerRepository->findOrFail($id);
        $query = $seller->items()->whereHas('baseItem');
        $totalSum = $query->get()->sum(function ($item) {
                return $item->baseItem->price->value;
            });
        $paginator = $query->paginate($request->get('_perPage', $this->sellerRepository->getPerPage()));
        $items = $paginator->items();

        $data = fractal()
            ->collection($items, new ItemTransformer())
            ->paginateWith(new IlluminatePaginatorAdapter($paginator))
            ->addMeta([
                'from' => $from->toDateString(),
                'till' => $till->toDateString(),
                'total_sum' => $totalSum,
                'page_sum' => collect($items)->sum(function ($item) {
                        return $item->baseItem->price->value;
                    }),
            ])
            ->toArray();

        return response()->json($data);
    }

感谢您的提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2011-08-21
    • 2019-11-01
    • 1970-01-01
    • 2020-10-19
    • 2012-02-27
    • 1970-01-01
    相关资源
    最近更新 更多