[英]Laravel Eloquent collection sortBy not taking effect
After eager loading attributes and their items I tried to sort the attributes without of luck. 在急切地加载属性及其项目之后,我尝试对属性进行排序而没有运气。
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
}
Can you please tell me why is that and how can I sort them with collections (not Eloquent and MySql)? 您能告诉我为什么吗,如何用集合(不是Eloquent和MySql)对它们进行排序?
Your problem is that you are not replacing the items in the collection itself. 您的问题是您没有替换集合本身中的项目。 So I believe a map
will do a better job here than a traditional foreach
. 因此,我认为map
在这里比传统的foreach
更好。 So try this instead and let me know: 因此,请尝试使用此方法,让我知道:
$attributes = $category->attributes->map(function($attribute) {
$attribute->items = $attribute->items->sortByDesc('name');
return $attribute;
});
dd($attributes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.