Search code examples
codeigniterdatamapperrelationships

DataMapper Self Relation Model


Hi I am using CodeIgniter with DataMapper and really need some help defining relationship in a model class (DataMapper Model Class)

How would I write the model relation for this. Slightly confused about the Self relation, i.e menu item and sub menu

Menu has many submenus and submenus can have one or more sub-submenus

Class: navigation
Table: Navigation
[id] [parent_id] [Name] ..

Thanks


Solution

  • This is a one-to-many relation (an item has one parent, a parent can have many items).

    So your model would look like:

    class Menu extends DataMapper {
    
        public $has_one = array(
            'parent' => array(
                'class' => 'menu',
            ),
        );
    
        public $has_many = array(
            'menu' => array(
                'class' => 'menu',
                    'other_field' => 'parent',
            ),
        );
    
    }
    

    This will allow you do do:

    // assume your tree root has parent id 0
    $root = new Menu();
    $root->where('parent_id', 0)->get();
    
    // get the first level menu from the root
    $submenu = $root->menu->get();
    
    // get the parent from the first submenu entry (should be root again)
    $rootagain = $submenu->parent->get();
    

    Note that (as I already replied on the CI forum) this is not a very optimal solution, as a tree can be several levels of nesting, with this setup it means having to iterate as you can only retrieve one level at the time, and for a single parent. This will become a nightmare for any size tree.

    Check out the nestedsets extension, which will allow you to build nested sets tree in a table, and adds the methods to Datamapper to manipulate those sets (like working with parents, children, syblings, inserting new records at specific locations in the tree, etc).