laravel groupBy 和 keyBy的区别

        $productCategory = ProductCategory::query()
            ->select('category_id', 'product_id', 'category_name')
            ->whereIn('product_id', $spuIdArr)
            ->where('status', ProductCategory::STATUS_VALID)
            ->get()
            ->groupBy('product_id')
            ->toArray();
// groupBy需要放在get()的后面,不然分组之后只有一条数据。

 

sortBy(),针对collection中的某一个字段进行排序(默认是升序排序)
$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();
/*
[
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
    ['name' => 'Desk', 'price' => 200],
]
*/

 

posted @ 2020-03-03 17:31  泥土里的绽放  阅读(3767)  评论(0编辑  收藏  举报