This is my first attempt at a HABTM in CakePHP and it's not going as well as I'd hoped.
I have table foos
and table bars
. When a foo
gets saved, I want to associate several bars
with it. I am attempting to do this with the bars_foos
bridge.
I'm wanting to be able to save in a way that I can pass a foo
along with a bunch of bars
something like:
array(2) {
["Foo"]=> array(1) {
["name"]=> string(7) "someFoo"
}
["Bar"]=> array(4) {
[0]=> array(1) {
["ID"]=> int(3)
}
[1]=> array(1) {
["ID"]=> int(9)
}
[2]=> array(1) {
["ID"]=> int(4)
}
[3]=> array(1) {
["ID"]=> int(15)
}
}
}
lets say someFoo
gets created with ID 9... I'd want the following records would be added to the bars_foos
table:
+--------+----------+
| bar_ID | foo_ID |
+--------+----------+
| 3 | 9 |
| 9 | 9 |
| 4 | 9 |
| 15 | 9 |
+--------+----------+
Currently nothing is happening in the bars_foos
table, only the foos
table is getting updated with the newly created "someFoo". The only time that this bridge should ever get updated is when creating a new Foo
I attempted to follow the CakePHP documentation with my model:
class Foo extends AppModel {
public $primaryKey = "ID";
public $hasAndBelongsToMany = array(
'Bar' =>
array(
'className' => 'Bar',
'joinTable' => 'bars_foos',
'foreignKey' => 'foo_ID',
'associationForeignKey' => 'bar_ID'
)
);
}
and using this in my controller...
$this->Foo->saveAll($data); //$data looks like the Array above in the first code block
I've also tried with my $data
in these formats based on things I've seen in searching for a solution:
array(1) {
["Foo"]=> array(3) {
["name"]=> string(7) "FooName"
["Bar"]=> array(2) {
[0]=> array(1) {
["ID"]=> int(3)
}
[1]=> array(1) {
["ID"]=> int(2)
}
}
}
}
and
array(2) {
["Foo"]=> array(1) {
["name"]=> string(7) "fooName"
}
["Bar"]=> array(1) {
["Bar"]=> array(2) {
[0]=> array(1) {
["ID"]=> int(3)
}
[1]=> array(1) {
["ID"]=> int(2)
}
}
}
}
and got the same result (new foo
gets created, but nothing gets inserted in the bars_foos
table)