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 Category extends\yii\db\ActiveRecord { publicfunction behaviors() {
return [
'tree'=> [
'class'=>NestedSetsBehavior::className(), 'treeAttribute' => 'tree',
// 'leftAttribute' => 'lft',
// 'rightAttribute' => 'rgt',
// 'depthAttribute' => 'depth',
],
];
}
publicfunction transactions() {
return [
self::SCENARIO_DEFAULT=>self::OP_ALL,
];
}
publicstaticfunction find() {
returnnew Category Query(get_called_class());
} }
4.创建分类查询器Category Query
use creocoder\nestedsets\NestedSetsQueryBehavior; class Category Query extends\yii\db\ActiveQuery { publicfunction 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();