我有一系列产品;每个都有一个包含多个项目的eloquent关系。
以下是我如何检索集合
$collections = Collection::with('items')->get();
这是控制器return $collections
的结果。
[
{
"id": 1,
"name": "Product One",
"items": [
{
"id": 1,
"product_id": 1,
"name": "Item One",
},
{
"id": 2,
"product_id": 1,
"name": "Item Two",
},
{
"id": 3,
"product_id": 1,
"name": "Item Three",
},
},
{
"id": 2,
"name": "Product Two",
"items": [
{
"id": 1,
"product_id": 2,
"name": "Item One",
},
{
"id": 2,
"product_id": 2,
"name": "Item Two",
},
{
"id": 3,
"product_id": 2,
"name": "Item Three",
},
}
]
我想按不同的顺序对每个产品的项目进行排序。
我希望将产品1的项目排序为3, 1, 2
,将产品2的项目排序排序为2, 3, 1
。
$sortOrder = [
1 => [3, 1, 2],
2 => [2, 3, 1]
];
$sorted = $products->map(function($product) use ($sortOrder) {
$order = $sortOrder[$product->id];
return [
...$product,
'items' => $product->items->mapWithKeys(
fn($item) => [array_search($item['id'], $order) => $item]
)->sortKeys()
];
});
This Outputs
Illuminate\Support\Collection {#4720
#items: array:2 [
0 => array:3 [
"id" => 1
"name" => "product one"
"items" => Illuminate\Support\Collection {#4722
#items: array:3 [
0 => array:2 [
"id" => 3
"name" => "three"
]
1 => array:2 [
"id" => 1
"name" => "one"
]
2 => array:2 [
"id" => 2
"name" => "two"
]
]
#escapeWhenCastingToString: false
}
]
1 => array:3 [
"id" => 2
"name" => "product two"
"items" => Illuminate\Support\Collection {#4721
#items: array:3 [
0 => array:2 [
"id" => 2
"name" => "two"
]
1 => array:2 [
"id" => 3
"name" => "three"
]
2 => array:2 [
"id" => 1
"name" => "one"
]
]
#escapeWhenCastingToString: false
}
]
]
#escapeWhenCastingToString: false
}