下面由laravel教程欄目給大家介紹laravel如何實(shí)現(xiàn)無(wú)限極分類,希望對(duì)需要的朋友有所幫助!
最近開(kāi)發(fā)商品功能,在嘗試遞歸和引用方式后,驀然回首,突然發(fā)現(xiàn)laravel框架有更簡(jiǎn)單高效的實(shí)現(xiàn)方式,無(wú)限極分類最佳實(shí)踐,open code與大家共享!感興趣的mark一下,謝謝~
表結(jié)構(gòu)如下:
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 '父級(jí)id', `level` tinyint(3) unsigned default '1' comment '分類等級(jí)', `status` tinyint(3) unsigned default '0' comment '分類狀態(tài):0-禁用,1-正常', `created_at` timestamp null default null comment '創(chuàng)建時(shí)間', `updated_at` timestamp null default null comment '更新時(shí)間', primary key (`id`) using btree, key `status` (`status`)) engine=innodb auto_increment=32 default charset=utf8mb4 comment='商品分類表';數(shù)據(jù)存儲(chǔ)格式:
業(yè)務(wù)代碼:
// 模型文件 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);處理后數(shù)據(jù):
至此,laravel框架無(wú)限極分類實(shí)現(xiàn)完畢,相比遞歸和引用實(shí)現(xiàn)無(wú)限極分類的兩種方式,是不是簡(jiǎn)單高效很多呢,關(guān)于更多l(xiāng)aravel特性,歡迎評(píng)論區(qū)留言探討。