如何在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
usecreocoder\nestedsets\NestedSetsBehavior;
classCategoryextends\yii\db\ActiveRecord{
publicfunctionbehaviors() {
return[
'tree'=>[
'class'=>NestedSetsBehavior::className(),
'treeAttribute' => 'tree',
// 'leftAttribute' => 'lft',
// 'rightAttribute' => 'rgt',
// 'depthAttribute' => 'depth',
],
];
}
publicfunctiontransactions() {
return[
self::SCENARIO_DEFAULT=>self::OP_ALL,
];
}
publicstaticfunctionfind() {
returnnewCategoryQuery(get_called_class());
} }
4.创建分类查询器CategoryQuery
usecreocoder\nestedsets\NestedSetsQueryBehavior;
classCategoryQueryextends\yii\db\ActiveQuery{
publicfunctionbehaviors() {
return[
NestedSetsQueryBehavior::className(),
];
} }
5.如何使用
创建一级分类
创建家用电器分类
$category1=newCategory(['name'=>'家用电器']);
$category1->makeRoot();
创建出来的树像下面这样
-家用电器
创建子分类大家电
$category2=newCategory(['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,转载请注明出处!