Laravel框架实现无限极分类


表结构如下:

CREATE TABLE `goods_category` (


  `id` int(11) NOT NULL AUTO_INCREMENT,


  `name` varchar(255) DEFAULT NULL COMMENT '分类名称',


  `pid` int(5) DEFAULT '0' COMMENT '父级id',


  `level` tinyint(3) DEFAULT '1' COMMENT '分类等级',


  `status` tinyint(3) DEFAULT '0' COMMENT '分类状态:0禁用 1正常',


  `created_at` datetime NOT NULL COMMENT '创建时间',


  `updated_at` datetime NOT NULL COMMENT '更新时间',


 PRIMARY KEY (`id`)


) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

数据存储格式:

 业务代码:

// 模型文件

public function children() {

    return $this->hasMany(get_class($this), 'pid' ,'id');

}


public function allChildren() {
return $this->children()->with( 'allChildren' )->where('status',1)->orderBy('level', 'asc');
 }
// 控制器
$list = GoodsCategory::with('allChildren')->where('pid', 0)->where('status', 1)->orderBy('level', 'asc')->get();

dd($list->toArray());

打印