雄辩的查询,用于返回按集合中的值分组的数组的总和


Eloquent query to return the sum of an array grouped by the values in a collecion

我正在构建一个使用纤细、树枝和雄辩的应用程序。在我的一个页面上,我展示了一组项目,首先分为两组,然后进一步按类别分成组。每个项目都有一个重量。我正在输出第一次拆分的所有项目的总重量。我从第二次拆分中输出每个类别的名称一次。现在,我想仅获取该类别中项目的总重量,并将其列在该类别名称下。

这是从路线:

$userId = $app->auth->id;
$collection = collect($app->item->where('user_id', $userId)->get()); // All items from the current user
$totalWeight = $collection->sum('grams');
$pack = $collection->filter(function($gear) { // All items with status 1 from the current user
    if ($gear->status === 1) {
        return true;
    }
})->sortBy('category');
$storage = $collection->filter(function($gear) { // All items with status 0 from the current user
    if ($gear->status === 0) {
        return true;
    }
})->sortBy('category');
$app->render('user/gear.php', [
    'pack' => $pack,
    'storage' => $storage,
    'totalWeight' => $totalWeight
]);

这是从以下视图:

<div class="pack">
    <header class="pack__header">
        <h2 class="pack__header__title">Backpack</h2>
        <span class="pack__header__weight">Total Weight: {{ totalWeight|outputWeights(totalWeight) }}</span>
    </header>
    {% set currentCategory = null %}
    {% for item in pack %}
        {% if item.category != currentCategory %}
            <h3 class="categoryName">{{ item.category|getCatName(item.category) }}</h3>
            {% set currentCategory = item.category %}
        {% endif %}
    <div class="item">
        <ul class="item__lineOne">
            <input type="checkbox" form="itemCheck" name="ID of the item" value="selected">
            <li class="item__lineOne__name">{{ item.name }}</li>
            <li class="item__lineOne__weight">{{ item.grams }}</li>
        </ul>
        <div class="collapse">
            <ul class="item__lineTwo">
                <li class="item__lineTwo__description">{{ item.description }}</li>
            </ul>
            <ul class="item__lineThree">
                <li class="item__lineThree__url">
                    <a class="item__lineThree__url__link" href="{{ item.url }}">{{ item.url }}</a>
                </li>
            </ul>
            <button type="button" class="modifyItemButton">Modify</button>
        </div>
    </div>
    {% endfor %}
</div>

我还有一个文件,其中包含一些Twig_SimpleFilters如果我需要在视图中的foreach期间使用一些代码。我只是不确定在哪里或什么有效的方法来解决这个问题。

  1. 您可以简化收集方法:

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

    而不是过滤器。

  2. 您不需要 sortyBy,请改用groupBy

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

    然后在模板中为每个类别使用sum

    {% for category,items in pack %}
      <h3 class="categoryName">{{ category|getCatName(item.category) }}
      <br>weight: {{ items.sum('grams') }}
      </h3>
      {% for item in items %}
        <div class="item"> ... </div>
      {% endfor %}
    {% endfor %}