在可翻译的 json 列上排序

Sorting on a translable json column

我在 laravel 中使用 spatie 翻译包。我有一个我想按名称排序的集合,但名称列有一个 json 集合,因此它没有得到排序。 我试过了

$shoptype->categories->sortBy('name.en');

和我的结果

{
"id": 8,
"type_id": 1,
"name": "{\"en\":\"Other Meats\",\"es\":\"Otras Carnes\"}",
"image_path": "http://market.test/uploads/category/Cpaf7nCVZxshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-08-14T06:17:35.000000Z",
"deleted_at": null
},
{
"id": 9,
"type_id": 1,
"name": "{\"en\":\"Turkey\",\"es\":\"Pavo\"}",
"image_path": "http://market.test/uploads/category/8U2qP2mrzashoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:01.000000Z",
"deleted_at": null
},
{
"id": 10,
"type_id": 1,
"name": "{\"en\":\"Chicken\",\"es\":\"Pollo\"}",
"image_path": "http://market.test/uploads/category/SnP7mwnTeBshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:14.000000Z",
"deleted_at": null
},
{
"id": 11,
"type_id": 1,
"name": "{\"en\":\"Beef\",\"es\":\"Carne De Vaca\"}",
"image_path": "http://market.test/uploads/category/b7IKzAGUHDshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:50.000000Z",
"deleted_at": null
}```




使用 SortBy 回调。

如果不是

,则使用collect方法将categories转换为collection
$categories = collect($shoptype->categories)->sortBy(function($category, $key){
       return (json_decode( $category->name))->en;
});

if $shoptype->categories 已经是一个集合

$categories = $shoptype->categories->sortBy(function($category, $key){
       return (json_decode( $category->name))->en;
});

如果 categories 是 Json 则使用 json_decode($shoptype->categories); 并使用 sortBycollect 方法

https://laravel.com/docs/8.x/collections#method-sortby