7th
MAY

HTree Hierarchial Model - a CodeIgniter Model

Posted by David under CodeIgniter Libraries

We needed a class that would retrieve a block of data with parent/child relationships from mySQL and store it in an array which correctly represents the three dimensional nature of the parent/child relationships. The class needed to also have methods for add, deleting and moving entries within and between categories.

What is the model for ?

Essentially we want to turn this:

PK  parent  name
-------------------------
1   0       Animals
2   1       Cat

Into this:

Array
(
    [0] => Array
        (
         [PK] => 1
         [parent] => 0
         [name] => Animals
         [childs] => Array
                        (
                        [0] => Array
                            (
                             [PK] => 2
                             [parent] => 1
                             [name] => Cat
                        )
        )
)

What can it do ?

The model contains simple functions to manage the data items such as:

$this->HModel->add_item("test item", 3);
$this->HModel->delete_item(53);
$this->HModel->move_item_down(14);
$this->HModel->is_item_live(21);

How do I use it ?

Simply copy the hierarchial_model.php file into the system/application/models folder within your CodeIgniter installation to complete the installation. Complete documentation is available in the HTree Hierarchial Model Guide.

Reader's Comments

  • Thank you for the useful library. I was in need of something like that.

    I am so embarrassed to say that cause I am a programmer too :) but I don’t have the time to write a library on my own.

    Thanx again !

    See ya.

  • You made some good points there.

  • Thanks a lot for this model, but I think there should be EDIT method :) !

  • I found a bug in the _is_item_at_top() function. When ‘home_mode’ is ‘0′ and ‘parent_id’ is ‘0′, the first top-level menu item was getting an ‘up_arrow’=1 and the second top-level menu item was getting a ‘up_arrow’=0. I modded the function to
    [code]
    function _is_item_at_top($item_PK) {
    $parent = $this->_get_parent($item_PK);
    if (isset($this->home_mode) || $parent == 0) {
    $append = 0;
    } else {
    $append = 1;
    }
    // get details of this item
    $this->db->where($this->PK_field, $item_PK);
    $query = $this->db->get($this->table);
    $item = $query->row_array();
    // if order position is 1 then item is at top of it’s section
    if ($item[$this->order_field] == (1 + $append)) {
    return 1;
    } else {
    return 0;
    }
    }
    [/code]

    and it seems to work now. I have not tested ‘home_mode’, but it looks like it should work. Nice library.

Leave a Reply

(required)
(will not be published) (required)

The Lab is the web development blog for PX Webdesign that covers many subjects from PHP, CSS, jQuery, CodeIgniter, Design and XHTML / HTML