我有一個示例表,如下所示:| id | is_new | cate || 0 | 1 | [5] || 1 | 1 | [5] || 2 | 1 | [7] || 3 | 1 | [6] |在我調用以下函數之后 $product = Products::where('is_new', 1)->get();該集合具有以下數據結構Collection {#1284 ▼ #items: array:4 [▼ 0 => Products {#1285 ?} 1 => Products {#1286 ?} 2 => Products {#1287 ?} 3 => Products {#1288 ?} ]}我還可以通過以下方式返回類別 ID 列表: $category = Category::where('type', 2)->pluck('id')->all(); 我想知道有沒有什么好的方法來實現基于 cate 的以下結構(或類似結構)。我可以使用蠻力方法通過循環 $category 然后手動添加到新集合來創建它,我認為有更好的方法來做到這一點。Collection {#1284 ▼ #items: array:3 [▼ 5 => array:2 [▼ 0 => Products {#1285 ?} 1 => Products {#1286 ?} ] 6 => Products {#1287 ?} or 6 => array:1 [ 0 => Products {#1287 ?} ] 7 => Products {#1288 ?} ]}基于答案的解決方案更新:$product->groupBy(function($item) { return $item['cate'][0]; //because the entry is a list });
1 回答

幕布斯7119047
TA貢獻1794條經驗 獲得超8個贊
- 1 回答
- 0 關注
- 242 瀏覽
添加回答
舉報
0/150
提交
取消