我有一个名为“products
”的数据库,其中有一列“categories
”。此表包含四类产品,即electronic
,Decoration
,clothes
和vehicle
。我的目标是显示这些category
与count
我e:if there are four products belongs to category electronic, then output should be like this :electronic=4
等等
我的代码
public function category()
{
$arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
$data = [];
foreach($arrayCategorys as $arrayCategory)
{
$sql = "SELECT count(id) FROM products WHERE categories='$arrayCategory'";
$records = \DB::select($sql);
$data = array_merge_recursive($data, [
"{$arrayCategory}" =>isset($records[0]->count),
]);
$data=array_filter($data);
dd($data);
}
}
我想要这样的节目输出
'electronic'=>'4',
'Decoration'=>'2',
'clothes'=>'2',
根据数据库中的数据, 'vehicle'=>'1'
但我什么都没得到,[]
答案 0 :(得分:1)
GROUP BY
COUNT
这样的方式SELECT categories,COUNT(*)
FROM products
GROUP BY categories;
$result = DB::table('products')
->select('products.categories',
DB::raw('count(products.id) as category_count')
)
->orderBy('products.id', 'asc')
->groupBy('products.categories')
->get();
编辑:虽然我不熟悉laravel5语法,但这可能适合你
OnGlobalLayoutListener
答案 1 :(得分:0)
您使用了isset($records[0]->count)
,但计数的列名称为count(id)
。将计数命名为count
,如此"SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'"
。并且你只能通过检查是否设置来获得计数。删除isset,然后使用$records[0]->count
。代码应如下所示:
public function category()
{
$arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
$data = [];
foreach($arrayCategorys as $arrayCategory)
{
$sql = "SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'";
$records = \DB::select($sql);
$data = array_merge_recursive($data, [
"{$arrayCategory}" =>$records[0]->count,
]);
$data=array_filter($data);
dd($data);
}
}