如何在Laravel中基于父子关联实现关联多表分类的无限层级菜单?
Laravel 无限层级产品分类菜单实现方案
前置修正
先修正products表字段笔误:将拼写错误的paren_id改为parent_id,避免后续关联逻辑出错。
1. 定义模型关联
Product 模型(app/Models/Product.php)
定义父子产品关联、产品与分类的关联,关联中预加载下层数据避免N+1查询问题:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; class Product extends Model { protected $fillable = ['name', 'project_id', 'parent_id']; // 关联子产品 public function children(): HasMany { return $this->hasMany(Product::class, 'parent_id') ->with('children', 'category'); // 预加载所有下级子产品和对应分类 } // 关联父产品 public function parent(): BelongsTo { return $this->belongsTo(Product::class, 'parent_id'); } // 关联对应分类 public function category(): HasOne { return $this->hasOne(Category::class); } }
Category 模型(app/Models/Category.php)
定义分类与产品的归属关联:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Category extends Model { protected $fillable = ['product_id', 'name']; // 关联所属产品 public function product(): BelongsTo { return $this->belongsTo(Product::class); } }
2. 获取树形结构数据
在控制器中直接查询顶级父产品,即可自动加载所有层级的子产品和对应分类:
// 控制器中调用 $productTree = Product::whereNull('parent_id') ->get();
返回的$productTree已经是嵌套的无限层级树形结构。
3. 前端渲染菜单
用Blade递归视图实现无限层级渲染:
第一步:新建递归子视图 resources/views/components/menu-item.blade.php
<li> {{ $item->name }} @if($item->category) <span>(分类:{{ $item->category->name }})</span> @endif @if($item->children->isNotEmpty()) <ul style="padding-left: 20px;"> @foreach($item->children as $child) @include('components.menu-item', ['item' => $child]) @endforeach </ul> @endif </li>
第二步:主视图中渲染完整菜单
<ul> @foreach($productTree as $rootItem) @include('components.menu-item', ['item' => $rootItem]) @endforeach </ul>
4. 实现效果
按照你提供的测试数据,最终渲染的菜单结构如下,完全符合预期的无限层级样式:
ParentProduct(分类:TopLevelProductCategory) ├── TopLevelOneProduct(分类:TopLevelCategory) │ ├── ToplevelOneProductChildFolder(分类:TopLevelOneProduct) │ │ └── TopLevelOneChildSubChildFolder(分类:TopLevelOneChildSubChildRequest) └── TopLevelTwoProduct
性能优化提示
如果产品层级超过10级、数据量过万,可使用嵌套集合扩展包kalnoy/nestedset优化查询性能,普通中小规模数据下上述方案足够使用。
内容的提问来源于stack exchange,提问作者Muhammad AbuBaker
相关产品推荐
相关产品推荐

