Home  >  Article  >  PHP Framework  >  How to implement infinite classification in Laravel

How to implement infinite classification in Laravel

藏色散人
藏色散人forward
2020-11-16 13:43:552128browse

The following tutorial column will introduce to you how Laravel implements Infinitus classification. I hope it will be helpful to friends in need! I recently developed product functions. After trying recursion and reference methods, I suddenly looked back and suddenly found that the laravel framework has a simpler and more efficient implementation method. Infinitus classification best practices, open code to share with everyone! Mark if interested, thank you~

The table structure is as follows:

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=32 DEFAULT CHARSET=utf8mb4 COMMENT='商品分类表';

Data storage format:

How to implement infinite classification in LaravelBusiness code:

    // 模型文件
    public function children() {
        return $this->hasMany(get_class($this), 'pid' ,'id');
    }

    public function allChildren() {
        return $this->children()->with( 'allChildren' );
    }
// 控制器$list = GoodsCategory::with('allChildren')->first();dd($list);

Processed data:

At this point, laravel The framework Infinitus classification has been implemented. Compared with the two ways of implementing Infinitus classification through recursion and reference, is it much simpler and more efficient? For more Laravel features, please leave a message in the comment area to discuss.

                                                                                                                                                                                            

The above is the detailed content of How to implement infinite classification in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete