Sunday, August 30, 2009

Emulate $hasAndBelongsToMany

Hi,

I've built a contact management system using $hasAndBelongsToMany and
I'm almost finished. I just found out that habtm associations don't
work across multiple databases.

I've gone through all the models and used $hasMany and $belongsTo
instead.

I liked the arrays I got using habtm and unfortunately, I'm not
getting the data the same way now.

Lets say I have these models
Individuals
Businesses

IndividualPhonenumbers
BusinessPhonenumbers

Phonenumbers

I have an element that will show all the Phonenumbers regardless of
who they belongs to (business or individuals)

with habtm it was as easy as:
foreach ($contacts as $contact):
$thisphonenumber = $contact['Phonenumber']['number'];
endforeach;

This made it easy to use a rather complex page for any entity that had
contact information.

Now, with the $hasMany and $belongsTo associations, my resulting array
includes the join models in them.
So now I have to know to do...
foreach ($contacts as $contact):
foreach ($contact['IndividualPhonenumber'] as $phonenumber):
$thisphonenumber = $phonenumber['Phonenumber']['number'];
endforeach;
endforeach;

The above code probably won't work, but I'm just illustrating the fact
that I have to deal with the join model, so now my code is not generic
and won't work the same way.

My question is this: I there a way to emulate the results I would get
from the habtm association using the new associations? According to a
"bug report" it looks like CakePHP will not allow habtm across
multiple databases any time soon. I wish there was some simple way of
getting the same arrays I was getting before or transforming the
arrays I get now into something easy to use.

Used To Get:
Array
(
[0] => Array
(
[Individual] => Array
(
[id] => 1
[name] => John Doe
[otherfields] =>
)

[Phonenumber] => Array
(
[id] => 1
[number] => 555-1212
)
etc.


Now I Get:
Array
(
[0] => Array
(
[Individual] => Array
(
[id] => 1
[name] => John Doe
[otherfields] =>
)

[IndividualPhonenumber] => Array
(
[id] => 1
[individual_id] => 1
[phonenumber_id] => 1
[Phonenumber] => Array
(
[id] => 1
[number] => 555-1212
)
)
etc.

Thanks,
Jesse
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: