最新有个项目需要从模型中查询最近的数组并去重旧的,一开始想要用到Groupby+Orderby
$boughts = Bought::whereIn('shopid', $shopid)->groupBy('userid')->orderBy('id', 'desc')->get()
先分组再排序,但是发现没有达到效果,上网查了下一堆抄袭怪基本都提到子查询,这样代码就比较啰嗦,翻了下Laravel手册发现使用unique()函数处理可以更简洁,代码如下:
$boughts = Bought::whereIn('shopid', $shopid)->orderBy('id', 'desc')->get()->unique('userid');
大概意思就是unique('key')可以指定从数组中键值靠前的保留而筛掉键值靠后的。
补充下Laravel[[官方手册]](https://laravel.com/docs/9.x/collections#method-unique )说明
The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
When dealing with nested arrays or objects, you may specify the key used to determine uniqueness:
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
Finally, you may also pass your own closure to the unique method to specify which value should determine an item's uniqueness:
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/
The unique method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the uniqueStrict method to filter using "strict" comparisons.
1 条评论
555