我正在从我的 动物 表,它与 岚,巗峃,。 表。我的问题是,我需要统计每个类别有多少产品被注册。
在Stackoverflow这里做了一个搜索,我开始使用下面的代码,它是返回每个类别的动物数量([动物,数量])。
$data = DB::table('animals')
->select(
DB::raw('category_id as category'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
$array[] = ['Name', 'Quantity'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->category, $value->number];
}
$cat = json_encode($array);
dd($cat);
使用 "dd",我看到下面的数据是正确的,但是category_id来了,我不知道如何获得这个id,并把这个id的类别名称。
"[["Category","Quantity"],[1,10],[2,14],[3,30],[4,26],[5,1]]"
例如:[2,14]这个指的是什么?[2,14] 这指的是category_id 2,它的名字是: 哺乳动物. 所以我将有14种动物登记在哺乳动物类别中。
我希望结果是这样的。
"[["Category","Quantity"],[birds,10],[mammals,14],[reptiles,30],[amphibians ,26],[fish,1]]"
我如何处理这个与类别名称相关的ID?
连接你的类别表,从那里得到名称,我想应该是这样的。
$data = DB::table('animals')
->join('category', 'animals.category_id', '=', 'category.id')
->select(
DB::raw('category.id as category_id'),
DB::raw('category.name as category_name'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
你可以使用模型中的 "withCount "方法,它可以帮助你计算一个关系中的结果数量。
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
请看文件 https:/laravel.comdocs7.xeloquent-relationships#counting-related-models。