Laravel框架实现无限极分类

表结构

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();

你可能感兴趣的:(laravel)