- 创建数据库
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 模型自动生成-优快云博客
- 编写代码
模型里面写方法
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);
}

本文介绍了在Laravel框架中创建数据库表`categories`的方法,以及使用两种方式获取具有父子关系的菜单:一是通过EloquentORM的递归查询,二是利用模型自动生成并实现递归获取所有子分类。
2570

被折叠的 条评论
为什么被折叠?



