在 Yii 中从数据库生成树 [英] Generating tree from database in Yii

查看:23
本文介绍了在 Yii 中从数据库生成树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Yii 中有一个表示树的模型,其中包含以下 MySQL 表:

I have a model in Yii which represents a tree, with the following MySQL table:

CREATE TABLE IF NOT EXISTS `nodes` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `node` varchar(255) NOT NULL,
    [ something more not necessary to display here ]
    `parentid` int(11) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`),
) ENGINE=InnoDB;

我对这个模型有以下关系:

I have the following relations for this model:

return array(
    'parentnode'=>array(self::BELONGS_TO, 'Nodes', 'parentid'),
    'childnode'=>array(self::HAS_MANY, 'Nodes', 'parentid'),
);

我使用 CTreeView 来显示树.使用 $model->childnode 递归迭代所有 parentid=0 的节点来构建源数组.这是迭代函数:

I am using CTreeView to display the tree. Building the source array with iterating all nodes with parentid=0 recursively using $model->childnode. This is the iterating function:

public static function nodetree($params) { //finds all top-level nodes
    $retval=array();
    $nodes=Nodes::model()->findAllByAttributes(array('parentid'=>0));
    foreach($nodes as $anode)
        $retval[]=Nodes::nodearray($anode, $params);
}

这是递归函数.

public static function nodearray($_node, $params) { // finds children
    $retval=array(
        'text'=>$_node->node, //may differ based on options
        'id'=>$_node->id,
        'expanded'=>false,    //may differ based on options
        'children'=>array(),
    );
    foreach ($_node->childnode as $c_node)
        $retval['children'][]=Nodes::nodearray($c_node, $params);
    return $retval;
}

由于 Yii 的开销,这可能不是最快的方法.在没有其他应用程序运行的开发服务器上,页面生成时间超过 1 秒.节点超过 1K,并在需要时由用户更新.

Probably this is not the fastest approach because of Yii's overhead. Page generation takes more than 1 second on a development server with no other application running. Nodes are more than 1K and are being updated by users when required.

如何更快地生成树/页面?

How can I generate the tree/page faster?

推荐答案

这是我目前测试过的最有效的方法.源自 http://blog.ideashower.com/post/15147134343/create-a-parent-child-array-structure-in-one-pass

This is the most efficient method as I tested upto now. Derived from http://blog.ideashower.com/post/15147134343/create-a-parent-child-array-structure-in-one-pass

public static function nodetree($param=array()) {
    $refs = array();
    $list = array();

    $nodes = Yii::app()->db->createCommand('select * from nodes')->queryAll();

    foreach ($nodes as $data) {
        $thisref = &$refs[ $data['id'] ];
        $thisref['parentid'] = $data['parentid'];
        $thisref['text'] = $data['node'];
        if ($data['parentid'] == 0) {
            $list[ $data['id'] ] = &$thisref;
        } else {
            $refs[ $data['parentid'] ]['children'][ $data['id'] ] = &$thisref;
        }   
    }           
    return $list;
}

这篇关于在 Yii 中从数据库生成树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆