基於yii2.0給大家做一個無限分類的實例,廢話不多說:
1、設計數據表,很簡單就三個字段
CREATE TABLE `category` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`cate_name` varchar(255) DEFAULT NULL,
`pid` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、model層代碼如下:
<?php
namespace common\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%category}}".
*
* @property string $id
* @property string $cate_name
* @property string $pid
*/
class Category extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%category}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['pid'], 'integer'],
[['cate_name'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'cate_name' => '分類名稱',
'pid' => '父級分類',
];
}
/**
* 獲取所有的分類
*/
public function getCategories()
{
$data = self::find()->all();
$data = ArrayHelper::toArray($data);
return $data;
}
/**
*遍歷出各個子類 獲得樹狀結構的數組
*/
public static function getTree($data,$pid = 0,$lev = 1)
{
$tree = [];
foreach($data as $value){
if($value['pid'] == $pid){
$value['cate_name'] = str_repeat('|___',$lev).$value['cate_name'];
$tree[] = $value;
$tree = array_merge($tree,self::getTree($data,$value['id'],$lev+1));
}
}
return $tree;
}
/**
* 得到相應 id 對應的 分類名 數組
*/
public function getOptions()
{
$data = $this->getCategories();
$tree = $this->getTree($data);
$list = ['添加頂級分類'];
foreach($tree as $value){
$list[$value['id']] = $value['cate_name'];
}
return $list;
}
}
3、控制器層聲明這樣一個方法
public function actionCreate()
{
$model = new Category();
$list = $model->getOptions();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'list' => $list
]);
}
}
4、視圖層代碼
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="category-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'cate_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model,'pid')->dropDownList($list)?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
5、效果圖如下