Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i use kohana framework and i am trying to code recursive function to create category tree.

My Categories Table

id      int(11)     NO  PRI     NULL    auto_increment
name    varchar(50)     NO      NULL     
parent_id   int(11)     NO      NULL     
projects_count  int(11)     NO      NULL     

My Example Which Is Not Work

public static function category_list($parent_id = 0)
{
    $result =  Database::instance()->query('
        SELECT name, projects_count 
        FROM project_categories
        WHERE parent_id = ?', 
        array($parent_id)
    );

    $project_categories = array();
    foreach($result as $row)
    {
        $project_categories[] = $row;

        Project_Categories_Model::factory()->category_list($parent_id + 1);
    }

    return $project_categories;
}
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Using this kind of hierarchical data implementation is highly non-optimal, because to get every subcategory you need do a separate query to the database. Like here you want to create recursion function.

If you still can change your table architecture please check Managing Hierarchical Data in MySQL.

This article describes a solution, how to fetch the whole hierarchy in one time query, so the recursive function will not be necessary.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.