表结构如下:
CREATE TABLE `goods_category` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id', `name` varchar(500) DEFAULT '' COMMENT '分类名称', `pid` int(5) unsigned DEFAULT '0' COMMENT '父级id', `level` tinyint(3) unsigned DEFAULT '1' COMMENT '分类等级', `status` tinyint(3) unsigned DEFAULT '0' COMMENT '分类状态:0-禁用,1-正常', `created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间', `updated_at` timestamp NULL DEFAULT NULL COMMENT '更新时间', PRIMARY KEY (`id`) USING BTREE, KEY `status` (`status`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='商品分类表';
添加数据
INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('1', '版本套餐', '0', '1', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('2', '图书', '0', '1', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('3', '组合会员', '1', '1', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('4', '考证会员', '3', '2', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('5', '初级会员', '3', '1', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('6', '经管类', '2', '2', '1', NULL, NULL); INSERT INTO `recruit_dev`.`goods_category` (`id`, `name`, `pid`, `level`, `status`, `created_at`, `updated_at`) VALUES ('7', '经济类', '2', '1', '0', NULL, NULL);
业务代码:
//模型 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());
打印
laravel框架无限极分类实现完毕,相比递归和引用实现无限极分类的两种方式,是不是简单高效很多呢
参考:https://mp.weixin.qq.com/s/HUuIJ4oEaxtT_wgXmojTaQ