-- -- 表的結構 `coverage` -- CREATE TABLE IF NOT EXISTS `coverage` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `pid` int(10) unsigned DEFAULT NULL, `coverageName` varchar(100) DEFAULT NULL, `coverageDesc` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ; -- -- 轉存表中的數據 `coverage` -- INSERT INTO `coverage` (`id`, `pid`, `coverageName`, `coverageDesc`) VALUES (16, NULL, '類別', ''), (17, 16, '類別一', ''), (18, NULL, '分類', ''), (19, 17, '類別二', ''); -- -- 限制表 `coverage` -- ALTER TABLE `coverage` ADD CONSTRAINT `coverage_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `coverage` (`id`) ON DELETE CASCADE;
然後才Controller中添加下面的代碼:
public function actionAjaxFillTree() { if (!Yii::app()->request->isAjaxRequest) { exit(); } $parentId = 'null'; if (isset($_GET['root']) and $_GET['root']!='source') { $parentId = (int) $_GET['root']; } $req = Yii::app()->db->createCommand( "SELECT m1.id, m1.coverageName AS text, m2.id IS NOT NULL AS hasChildren " . "FROM coverage AS m1 LEFT JOIN coverage AS m2 ON m1.id=m2.pid " . "WHERE m1.pid <=> $parentId " . "GROUP BY m1.id ORDER BY m1.coverageName ASC" ); $children = $req->queryAll(); echo str_replace( '"hasChildren":"0"', '"hasChildren":false', CTreeView::saveDataAsJson($children), ); exit(); }
然後在views中添加如下代碼:
$this->widget('CTreeView',array( 'persist'=>'cookie', 'animated'=>'fast', 'url' => array('ajaxFillTree'), 'htmlOptions'=>array( 'id'=>'coverageTree', 'class'=>'coverageTree' ) ));
done!