return 一个新的 Eloquent 集合,其中一列的值已修改

return a new Eloquent collection with modified values from one column

我有一个 Slim 应用程序,它使用存储多个项目的数据库。每件物品的重量都以克为单位存储。我想允许用户在公制和美国常用单位(磅和盎司)之间切换。当我输出项目时,我以几种不同的方式按类别对它们进行分组,并按类别给出总和。除非从克到盎司的转换是预先完成的(在路线文件中),否则数学将无法工作,因为我必须四舍五入。我不想让我的盎司有任何小数。

我将在其中添加一个 if 语句来检查用户使用的是公制还是美制。如果他们使用美国,我想将克列中的值修改为盎司,然后 return 整个系列,但我不确定如何完成此操作。

transform()map() 方法似乎可以执行此操作,但我无法 select 我想要更改的各个列值。该文档仅显示了这些方法在非常简单的平面集合上的工作情况。我以为我可以使用 merge(),但只有当我要合并的数组与我要覆盖的数组中的键相同时,它才会起作用。

<?php

use Cache\Gear\Gear;

$app->get('/:username/gear', $authenticated(), function() use($app) {

$userId = $app->auth->id;

$collection = collect($app->item->where('user_id', $userId)->get());

$pack = $collection->where('status', 1)->groupBy('category');

// if user is using US customary units
    // Convert grams to ounces and return the collection

// else user is using metric
    // $totalWeight = $collection->where('status', 1)->sum('grams');

$storage = $collection->where('status', 0)->groupBy('category');

$app->render('user/gear.php', [
    'pack' => $pack,
    'storage' => $storage,
    'totalWeight' => $totalWeight
]);

你在 transform 的正确轨道上:

$collection->transform(function ($item, $key) {
    $item->grams = $item->grams*0.035274;
    return $item;
});