php - 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)对它们进行排序?
解决方案
您的问题是您没有替换集合本身中的项目。所以我相信 amap
会比传统的foreach
. 所以试试这个,让我知道:
$attributes = $category->attributes->map(function($attribute) {
$attribute->items = $attribute->items->sortByDesc('name');
return $attribute;
});
dd($attributes);
推荐阅读
- javascript - JS 中的作用域:这些变量不应该是全局的,而是在没有“var”或“let”的情况下声明。为什么?
- ios - 未调用 UI 更新委托方法
- progressive-web-apps - 渐进式网络应用
- html - 按钮订单具有不同的上边距,即使它们具有相同的 css 文件
- sqlite - 找不到类型“本地:EmailValidationBehavior”?
- c++ - C++ 继承向量问题(无限循环+在其他类中使用向量的问题)
- python - 按 0 级索引的最后一个值对 Pandas MultiIndex 进行排序
- pine-script - 由于某些未知原因,未绘制某些阻力
- node.js - Botframework 如何首先进行身份验证,然后使用令牌进行图形 API 调用
- javascript - 我正在尝试将 base64 编码的字符串转换为我的反应文件上的图像