Welcome Guest, Not a member yet? Register   Sign In
Datamapper advanced relationship question
#1

[eluser]Haskabab[/eluser]
Hey,

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:
Code:
$location->child->name
or
Code:
$location->sublocations
Code:
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,

Nick
#2

[eluser]WanWizard[/eluser]
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
Code:
// get the 'cavern' location
$location = new Location();
$location->get_by_name('Cavern');

// get all sublocations
$location->sublocation->get();

// 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.
#3

[eluser]Haskabab[/eluser]
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?
#4

[eluser]WanWizard[/eluser]
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:
Code:
$grandparent->parent->child->grandchild->where('field', 'value')->get();




Theme © iAndrew 2016 - Forum software by © MyBB