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

How to implement infinite classification in Laravel

藏色散人
Release: 2020-11-16 13:43:55
forward
2235 people have browsed it

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='商品分类表';
Copy after login

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' );
    }
Copy after login
// 控制器$list = GoodsCategory::with('allChildren')->first();dd($list);
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template