我需要通过收集产品来查看产品表中最热门的刀片类别,并对它们的类别进行计数并对其分类结果进行排序
$popular_channels = products::select('category')->get();
$collection = collect($popular_products);
$counted = $collection->countBy(function ($value){
return $value['category'];
});
$sorted = array_values(Arr::sort($counted, function ($values) {
return $values['category'];
}));
$counted = json_decode($counted,JSON_UNESCAPED_UNICODE);
$popular = channels::query();
foreach ($counted as $key=>$value)
{
$popular = $popular->where('id', $key);
}
$popular = $popular->offset(0)->limit(3)->orderby('id','desc')->get();
答案 0 :(得分:0)
除了我的解决方案外,您的代码还有一些我不清楚的地方:
$popular_channels
的数组,然后在最后几行中将频道模型引入$popular
数组中?$sorted
数组的用途是什么?categories
ID,然后使用类别表中的ID在ID列上过滤channels
。这些是否相关或以任何方式连接?还有一些可能有用的注释:
get
方法返回一个collection
实例,因此您实际上不需要调用collect
方法whereIn($field, $keys)
要正确,完整地回答,也许您应该从迁移/数据库结构和模型类中摘录,但要进行一些调整(列名,表名,模型,错别字等),此查询应该这样做:< / p>
$populars = DB::table('products')
->selectRaw('category_id, count(*) as productsCount'))
->groupBy('category_id')
->orderBy('productsCount', 'desc')
->limit(3)
->get()
->toArray();
$channels = channels::whereIn('id', $populars)
->orderByRaw('FIELD(id,' . implode(',', $populars) . ')') // Preserve the I'd order as retrieved before
->get();