我正在尝试从我的产品表中获取独特品牌的数量以及它们在 Laravel 集合中的数量。
我能够使用产品的特定查询来做到这一点,但我现在使用集合的原因是因为我还想获得产品的产品来源(国家/地区)、条件(二手/新)和我认为使用一个查询中的集合比对每个数据进行三个单独的查询要好得多。
下面的代码有效,但它没有显示每个独特品牌的数量。
这是我的 Controller
$products = DB::table('products')
->select('products.*')
->whereNull('products.deleted_at')
->get();
$BrandCollection = collect($products);
$Brands = $BrandCollection->unique('Brand')->sortBy('Brand')->keyBy('Brand')->pluck('Brand');
所以,我要找的结果是
HP 3
东芝2
联想1
我认为可以使用 concat 来收集,但由于我使用的是 Laravel 5.2,所以我正在寻找其他解决方案。
最佳答案
如果你真的想使用集合(不是 Eloquent),你可以这样做:
$brandsWithCount = $BrandCollection->groupBy('Brand')->map(function($values) {
return $values->count();
})->sort()->reverse();
例如,如果您像这样设置 $brandCollection
:
$BrandCollection = collect([
['Brand' => 'HP'],
['Brand' => 'HP'],
['Brand' => 'HP'],
['Brand' => 'Toshiba'],
['Brand' => 'Toshiba'],
['Brand' => 'Lenovo'],
]);
结果将是:
Collection {#372
#items: array:3 [
"HP" => 3
"Toshiba" => 2
"Lenovo" => 1
]
}
正如预期的那样。
关于php - 使用 Laravel 5.2 集合中的列名获取唯一值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46696079/