我想要获得一个类别树来显示它,如下所示:
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`)
)所以每条记录只包含self和parent id (我不能添加left和right 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'
)
)
),
...因此,基本上我得到了Category对象的数组(这些对象的数量是类别的数量(全部,甚至是子类别)。每个类别都有一个父类别和子类别数组...
这不是我想要的,因为我必须“手动”解析数组来构建类别树,而且速度会很慢,因为我必须在数组中查找具有指定id的类别(类别id不是它在数组中的索引)……
也许some1知道什么特殊的技巧来获得一个漂亮的,有用的分类树?
发布于 2012-04-23 01:47:21
尝试查看find方法的其他参数。您可以尝试使用
$res = $this->Category->find('threaded');你可以在http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-threaded上找到更多细节。
https://stackoverflow.com/questions/10270319
复制相似问题