0
votes

I am trying to save an array like this

$myData = array(
    'User' => array('id' => 17),
    'Group' => array(
        array('group_id' => 2),
        array('group_id' => 3),
        array('group_id' => 4),
        array('group_id' => 5),
        array('group_id' => 6)
    )
);

In my HABTM join table (groups_users). I tried the following save calls, but none of them worked.

$this->User->save($myData);
$this->User->saveAssociated($myData);
$this->User->saveAll($myData);
$this->User->GroupsUsers->save($myData);
$this->User->GroupsUsers->saveAll($myData);

Before you ask: Yes, my associations are set-up correctly and I was able to save data by calling:

$this->User->GroupsUsers->saveAll(array(
    0 => array(
        'GroupsUsers' => array('user_id' => $id, 'group_id' => 1)
    ),
    1 => array(
        'GroupsUsers' => array('user_id' => $id, 'group_id' => 2)
    )
));

BUT only one of both records are saved, although I set unique to false in the model's HABTM relationship definition.

Where is the error? Is the structure of my array invalid?

3

3 Answers

0
votes

The problem is that your data array is incorrectly formatted.

Your Group model will probably have an id field, and your join model GroupsUser will have a group_id field.

So you need to change your group_id to id

0
votes

try

$myData = array(
    'User' => array('id' => 17),
    'Group' => array(
        'Group' => array(
            0 => 2,
            1 => 3,
            2 => 4,
            3 => 5,
            4 => 6
        )
    )
);
0
votes

Just to answer your question even if it's old.

You doesn't have to call your 'GroupsUsers' model in your saveAll call, this is precisely the goal of associating Models, cakePHP does that for you.

You should pass this array to a saveAll function on your User/Group model:

array{
    array{
        'User' => array {
             'id' => 25
         },
         'Group' => array {
             'id' => 2
         }
    }
    array{
        'User' => array {
             'id' => 47
         },
         'Group' => array {
             'id' => 2
         }
    }
}

Both your User and Group Models should have and HABTM relation with each other, so that you just have to do that:

From the User/Group controller:

$this->User/Group->SaveAll($myData);

From the User/Group Model:

$this->SaveAll($myData);

And that's it, the GroupsUsers table will save 2 records, by saving by yourself in the HABTM relation table, you are not using the power of cakePHP.

And the records in both User and Group tables will be created if the ID doesn't exist, updated if not.

The only reason to save in an HABTM table is if you have some extra information you want to save in this table such as a 'validated' fields if you want to validate a member after he asked to join a group for example.