1

I'm stuck and reading the documentation doesn't seem to be helping me out.

I have one to many relationships working, all though I'm sure there is an easier way, I'm stuck when it comes to Many to Many relationships.

I've tried quite a few things, but basically I have three tables:

homes:
- id
- address_id
- price
- etc

features:
- id
- name

features_homes
- id
- feature_id
- home_id

I've setup my model quite a few different ways.

var $has_many = array(
    'feature' => array(
        'class' => 'feature',
        'other_field' => 'home',
        'join_self_as' => 'home',
        'join_other_as' => 'feature',
        'join_table' => 'features_homes'
    )
);

And the basic version of

var $has_many = array('feature');

The problem is I can't figure out how to get multiple records associated with the home.

I end up with a single item rather than a group of items.

Example output:

[id] => 1
[address_id] => 1
[latlong] => 00.000, -00.00000
...
[feature_id] => 1
[feature_name] => Hard Wood Floors

I am trying to get

[id] => 1
[address_id] => 1
[latlong] => 00.000, -00.00000
...
[features] => // Object of all items
tereško
  • 58,060
  • 25
  • 98
  • 150
Seth
  • 6,240
  • 3
  • 28
  • 44

1 Answers1

1

You associate one object to another by linking them when you save.

You can do that multiple times:

$parent = new Parent(1);
$childA = new Child(1);
$childB = new Child(2);

$parent->save($childA); $parent->save($childB);

Or by passing an array:

$parent = new Parent(1);
$children = array(
    new Child(1),
    new Child(2),
);

$parent->save($children);
WanWizard
  • 2,574
  • 15
  • 13
  • What if you already have this data saved in a database that you are trying to access? Do you have to save everything with DataMapper before you can display it the way you want? – Seth Apr 03 '12 at 12:18
  • Then you'll fetch them instead of creating them. – WanWizard Apr 06 '12 at 20:23
  • The framework is really cool, but I think I need to keep beating it up to really figure it out. I have something that just isn't right, and I'm sure it's my code. Do you know of any good tutorials online that walk your through different scenarios? I was able to get the results I was looking for, but I had to do a loop inside a loop to get the data. I think my models need to be changed somehow so I can group multiple results under a single key in the object. – Seth Apr 07 '12 at 00:08
  • Quick question...so I just discovered this, `$obj->subobj->all` is this the best way to get all the related objects? – Seth Apr 07 '12 at 04:47
  • Yes. All Datamapper objects implement ArrayIterator, so you can simply foreach over $obj->subobj without having to be bothered with the all array. – WanWizard May 07 '12 at 10:53
  • Can you take a peek at this question when you have time. http://stackoverflow.com/questions/10593008/datamapper-all-to-json-method-returning-slashes – Seth May 15 '12 at 01:52