2

Q: How to set models for Adjacency Lists, when using Datamapper ORM. Anyone experienced ? For example, Table Category ( id, name, has_parent_category_id ). Thanks for looking!

Example table,

Tbl Category

id | name | has_parent_category_id
1  | catA | 0
2  | catB | 0
3  | catC | 1
4  | catD | 2
5  | catE | 3

The docs are in http://datamapper.wanwizard.eu/pages/advancedrelations.html and I found the following "Self Relationships". I'm not sure if this is the right way! I'm testing it.

If anyone is experienced with Adjacency lists, codeigniters Datamapper ORM and would mind leaving one practical example on how to do this, I would appreciate it!

Thanks for your time!

punkbit
  • 7,347
  • 10
  • 55
  • 89

1 Answers1

0

(Note: I haven't used DataMapper much since I handed the reigns over to WanWizard, but I maintained DMZ for quite a while.)

I see two possible solutions:

1) Assuming any two vertexes can only have one common edge

In the case of a single edge per vertex pair, you don't need to do anything special. Simply create a new standard self-relationship (ie: a named one) to represent the connection:

$has_many = array(

    'parent_category' => array(
        'class' => 'category'
        'other_field' => 'category'
    ),
    'category' => array(
        'other_field' => 'parent_category'
    )
);

Then create your joining table like this:

name:    categories_parent_categories
columns: id | category_id | parent_category_id

Now you can easily make your edges like this:

$catA = new Category()
$catA->name = 'catA';
$catA->save();
$catB = new Category();
$catB->name = 'catB';
$catB->save();
$catA->save('parent_category', $catB);
// OR
$catA->save_parent_category($catB);

$catA->parent_category->get();
foreach($catA->parent_category as $parent) {
    echo $parent->name;
}

See http://datamapper.wanwizard.eu/pages/save.html#Advanced for more info on saving these kinds of relationships.

2) Assuming you need multiple edges per vertex

This is a much more complicated example, but it basically involves creating a dedicated object to represent the relationship, because DataMapper doesn't allow two objects to be related more than once per relationship type.

If you want this example, let me know, and I'll write something up, or check out http://datamapper.wanwizard.eu/pages/troubleshooting.html#Relationships.NtoM

OverZealous
  • 39,252
  • 15
  • 98
  • 100
  • Could you possibly check this question? Much appreciated http://stackoverflow.com/questions/24235025/joining-tables-using-orm-datamapper-codeigniter – Sobiaholic Jun 16 '14 at 13:28