效果图
表:
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‘, PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8mb4 COMMENT=‘商品分类表‘;
Laravel模型层:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class GoodsCategory extends Model { // public $table = ‘goods_category‘; public function children() { return $this->hasMany(get_class($this), ‘pid‘ ,‘id‘); } public function allChildren() { return $this->children()->with( ‘allChildren‘ ); } }
Laravel控制器
function test(){ $list = GoodsCategory::with(‘allChildren‘)->first(); return $list; }