• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Datamapper advanced relationship question


If i post this in the wrong forum, I'm sorry for that. I wasn't sure where to post this.

But I've been using DataMapper ORM and I'm loving it so far. Now I've run into a problem: I don't know how to setup relationships for the following db tables:

Location -- (contains coordinates of the location)
This location can have several children: 'Village' or 'Hideout' or 'Cavern'.

Within this Location there can be several Sublocations (one-to-many)
This sublocation again, can have several children: 'Shop' or 'Hospital'

Normally I would add the fields 'type' and 'db_id' and write a function 'getChild()' to get the child depending on the type. But how do I do this in datamapper?

To get something like:
foreach( $sublocations as $sublocation ){ echo $sublocation->type.': '.$sublocation->child->name

I've searched the documentation but I didn't find anything related to this. So if you know how to do this, I would really appreciate it if you told me!

Thanks in advance,


With 'children' you mean values?

Assuming that you have a model Location, and a model Sublocation, and a one-to-many relation between the two, you use
// get the 'cavern' location
$location = new Location();

// get all sublocations

// print them
echo $location->name, '<br />';
foreach ($location->sublocation as $sl)
    echo $sl->type, $sl->name, '<br />';

Start reading here, and then use the 'next topic' link in the footer to go to the next page. It will explain how relations are defined, and how you access them.

Yeah the relationship between the location and sublocation is easy.

But where I'm stuck is how to setup the relation between the location. And the different kind of locations.

A location can either be linked to:

1. Village
2. Cavern
3. Hideout
4. Fortress

these "children" all have their own table, and tables related to those. As i will write modules for them.

And the sublocation can either be linked to:

1. Shop
2. Hospital
3. Academy
4. Square
5. A lot more..

same goes for these children

Do you understand what I mean?

Just make an ER diagram, showing all the tables, primary and foreign keys, and their relations. On paper of with some tool. I personally use Visio as it is platform agnostic, but you can also use MySQL Workbench.

From there it's pretty easy to define the models and their relationships.

In your code, you can just chain the relations, it doesn't matter how deep:
$grandparent->parent->child->grandchild->where('field', 'value')->get();

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.