yii2框架中使用嵌套集合实现无限极商品分类

来源:互联网 发布:竞翔通软件 编辑:程序博客网 时间:2024/06/05 12:41

如何在yii2框架中使用嵌套集合实现无限极商品分类呢?来看看源码时代老师的解答!

1.使用composer安装nested_sets插件

composer require creocoder/yii2-nested-sets

2.创建商品分类表的数据迁移

 yii migrate/create create_category_table

数据迁移类的内容如下:

$this->createTable('{{%category}}', [     

'id' => $this->primaryKey(),    

 'tree' => $this->integer()->notNull(),    

 'lft' => $this->integer()->notNull(),    

 'rgt' => $this->integer()->notNull(),    

 'depth' => $this->integer()->notNull(),     

'name' => $this->string()->notNull(),

]);


3.创建商品分类活动记录Category

use creocoder\nestedsets\NestedSetsBehavior;

class Categoryextends \yii\db\ActiveRecord {     

public function behaviors() {        

 return [             

'tree' => [                

 'class' => NestedSetsBehavior::className(),                  

'treeAttribute' => 'tree',                

 // 'leftAttribute' => 'lft',                 

// 'rightAttribute' => 'rgt',                 

// 'depthAttribute' => 'depth',            

 ],         

];     

}      

public function transactions()     {         

return [             

self::SCENARIO_DEFAULT => self::OP_ALL,        

 ];     

}      

public static function find()     {         

return new CategoryQuery(get_called_class());     

} }

 

4.创建分类查询器CategoryQuery

use creocoder\nestedsets\NestedSetsQueryBehavior;

class CategoryQuery extends \yii\db\ActiveQuery {     

public function behaviors() {         

return [             

NestedSetsQueryBehavior::className(),        

 ];    

 } }

 

 

5.如何使用

创建一级分类

创建家用电器分类

$category1 = new Category(['name' => '家用电器']);

$category1 ->makeRoot();

创建出来的树像下面这样

- 家用电器

创建子分类大家电

$category2 = new Category(['name' => '大家电']);

$category2 ->prependTo($category1);

结构如下

- 家用电器

- 大家电

 

获取所有一级分类

$roots = Category::find()->roots()->all();

获取所有子分类

$leaves = Category::find()->leaves()->all();

获取某分类的所有子孙分类

$category1 = Category::findOne(['name' => '家用电器']); $leaves = $category1->leaves()->all();

获取某节点的所有子分类

$category1 = Category::findOne(['name' => '家用电器']); $children = $category1->children()->all();

获取某分类的第一个子分类

$category1 = Category::findOne(['name' => '家用电器']); $children = $category1->children(1)->all();

获取某分类的所有父分类

$category2= Category::findOne(['name' => '大家电']); $parents = $category2->parents()->all();

获取某分类的第一个父分类

$category2= Category::findOne(['name' => '大家电']); $parent = $category2->parents(1)->one();

本文来源:http://bbs.itsource.cn/thread-1502-1-1.html,转载请注明出处!