You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何在父分类旁显示子分类数量

实现父分类显示子分类数量的两种方案

方法一:Eloquent关联 + withCount(推荐)

先在Category模型中定义子分类的关联关系:

// app/Models/Category.php
class Category extends Model
{
    // 关联子分类:当前分类的所有子分类
    public function children()
    {
        return $this->hasMany(Category::class, 'parent', 'id');
    }
}

修改控制器查询逻辑,用withCount预加载子分类数量(避免N+1查询问题):

public function index()
{
    $arr['categories'] = Category::where('parent', null)
        ->orderBy('category', 'asc')
        ->withCount('children') // 自动生成`children_count`字段存储子分类数量
        ->get();
    return view("admin.categories")->with($arr);
}

最后修改视图,替换原来的<td>#</td>为数量展示:

<td>{{ $item->children_count }}</td>

方法二:直接在查询中嵌入子统计(无需模型关联)

如果不想定义模型关联,可直接通过子查询统计数量:

public function index()
{
    $arr['categories'] = Category::select('categories.*')
        ->selectRaw('(SELECT COUNT(*) FROM categories AS child WHERE child.parent = categories.id) AS children_count')
        ->where('parent', null)
        ->orderBy('category', 'asc')
        ->get();
    return view("admin.categories")->with($arr);
}

视图修改和方法一一致,直接用{{ $item->children_count }}显示子分类数量即可。

内容的提问来源于stack exchange,提问作者adsegzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:54:22