首页 > 解决方案 > Laravel Eloquent 集合排序不生效

问题描述

在急切加载属性及其项目后,我尝试对属性进行排序,但没有运气。

public function __invoke(Category $category)
    {
        $category->load(['attributes']);

        $category->attributes->load(['items' => function ($query) use ($category) {
            $query->whereHas('productVariations.product.categories', function ($query) use ($category) {
                $query->where('categories.id', $category->id);
            });
        }]);
        foreach ($category->attributes as $attribute) {
            $attribute->items = $attribute->items->sortByDesc('name');
        }

        dump($category->attributes->first()->items->pluck('name')); // Items are sorted
        dd($category->attributes->toArray()); // Items are not sorted
     }

你能告诉我为什么会这样吗?我怎样才能用集合(不是 Eloquent 和 MySql)对它们进行排序?

标签: phpmysqllaravelcollectionseloquent

解决方案


您的问题是您没有替换集合本身中的项目。所以我相信 amap会比传统的foreach. 所以试试这个,让我知道:

$attributes = $category->attributes->map(function($attribute) {
  $attribute->items = $attribute->items->sortByDesc('name');
  return $attribute;
});

dd($attributes);

推荐阅读