我想得到一个类别树来显示它:
cat1
subcat1
subcat2
subcat3
subsubcat1
cat2
subcat1
...
我有这张桌子:
CREATE TABLE IF NOT EXISTS `kategorie` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(256) collate utf8_polish_ci NOT NULL,
`father` int(11) NOT NULL default '-7',
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
)
所以每条记录只包含自己和父ID(我不能添加左右ID)。
现在我制作了这个模型:
class Category extends AppModel
{
public $name = 'Category';
public $useDbConfig = 'external';
public $useTable = 'kategorie';
var $belongsTo = array(
'ParentCategory' => array(
'className' => 'Category',
'foreignKey' => 'father'
));
var $hasMany = array(
'ChildCategory' => array(
'className' => 'Category',
'foreignKey' => 'father'
));
}
和控制器:
class CategoriesController extends AppController {
public function beforeFilter()
{
parent::beforeFilter();
//$this->Auth->allow('add','logout');
}
public function index()
{
$res = $this->Category->find('all');
//$this->set('categories', $this->Category->find('all') );
debug($res); die;
}
}
调试输出是这样的:
array(
(int) 0 => array(
'Category' => array(
'id' => '1',
'name' => 'catname',
'father' => '2'
),
'ParentCategory' => array(
'id' => '2',
'name' => 'catname',
'father' => '3'
),
'ChildCategory' => array(
(int) 0 => array(
'id' => '161',
'name' => 'catname',
'father' => '1'
)
)
),
(int) 1 => array(
'Category' => array(
'id' => '2',
'name' => 'catname',
'father' => '3'
),
'ParentCategory' => array(
'id' => '3',
'name' => 'catname',
'father' => '4'
),
'ChildCategory' => array(
(int) 0 => array(
'id' => '1',
'name' => 'catname',
'father' => '2'
),
(int) 1 => array(
'id' => '5',
'name' => 'catname',
'father' => '2'
),
(int) 2 => array(
'id' => '489',
'name' => 'catname',
'father' => '2'
)
)
),
...
所以基本上我得到类别对象的数组(这些对象的数量是类别的数量(全部,甚至是子类别)。每个类别都有一个父类别和子类别数组......
这不是我想要的,因为我必须“手动”解析数组以构建类别树,而且速度会很慢,因为我必须在数组中找到具有指定 id 的类别(类别 id 不是它在数组中的索引) ...
也许 some1 知道任何特殊技巧来获得一个漂亮、有用的类别树?