表构造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);模型关联/** * 查找本人的子级 * @return \Illuminate\Database\Eloquent\Relations\HasMany */public function children() { return $this->hasMany(get_class($this), 'pid' ,'id');}/** * 有限分级 * @return \Illuminate\Database\Eloquent\Relations\HasMany */public function allChildren() { return $this->children()->with( 'allChildren' )->where('status',1)->orderBy('level','asc');}控制器调用$items = GoodsCategory::with('allChildren')->where('pid',0)->where('status',1)->orderBy('level','asc')->get();