Laravel 无限极分类

  • 创建数据库
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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值