- 创建数据库
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父ID',
`name` varchar(512) NOT NULL COMMENT '分类名称',
`updated_at` timestamp NULL DEFAULT NULL COMMENT '更新时间',
`created_at` timestamp NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='无限极分类';
第一种方式
public function getMenu($parent_id){
$menus = DB::table('category')->where('parent_id', $parent_id)->get();
foreach ($menus as $menu) {
$menu->children = $this->getMenu($menu->id);
}
return $menus;
}
路由
Route::get('category/{id}','Category@getMenu');
第二种方式
- 模型生成
快速生成模型:Laravel 模型自动生成-CSDN博客
- 编写代码
模型里面写方法
public function getAllCategories($parentId = 0){
$categories = $this->where('parent_id', $parentId)->get();
foreach ($categories as &$category) {
$category['children'] = $this->getAllCategories($category['id']);
}
return $categories;
}
控制器引用模型
public function category(){
$categoryModel = new Test();
$categories = $categoryModel->getAllCategories();
return $this->success($categories);
}