0
votes

I have the following association:

Group hasAndBelongsToMany User, with the groups_users join table.

When I create a new group, I want to add to the join table the founder of the group.

My $this->data array looks like:

Array
     (
[Group] => Array
    (
        [name] => seyufgsduifsj
        [access] => 2
        [founder_id] => 3
        [random_key] => I6XC7uMTelpTSdq8DbtLPjqubiF7s6Pn
    )

[GroupsUser] => Array
    (
        [user_id] => 3
        [group_role_id] => 1
        [random_key] => PZsDZXcoCTHw1IuvqsfURVpPX6AcZ3r2
    )

)

I tried with save() and saveAll(), but it would add only the group in the groups table and not the user-group association.

So, basically, I have an add form where the user fills in the group name and access. Then, if the data validates, I add a couple of more field values to the group array (like random_key) and to the join table array (like user_id and group_role_id). I want Cake to save the group first, take its id, update the join table array with the proper group_id, and then save this second array too.

Is this possible in a straight-forward way, or do I have to write two consequent save() methods, for the second one providing the last inserted id in the first one?

Thanks!

2

2 Answers

0
votes

Perhaps the related models are not passing validation. Use the following piece of code to save only if all models validate:

$this->Group->saveAll($this->data, array('validate' => 'only'));

If you don't find your Group being saved this time around, then it's most probably validation rules in your Join Model that are failing. My guess is that you have a notEmpty validation for the group_id, which you would have to remove in order for saveAll() to work.

Hope this points you in the direction of solving your problem.


EDIT: Your associations are a little off. Here's what it should be:

Group hasMany GroupsUser
User hasMany GroupsUser
GroupRole hasMany GroupsUser
GroupsUser belongsTo Group
GroupsUser belongsTo User
GroupsUser belongsTo GroupRole

Remove the hasAndBelongsToMany association between Groups and User. It doesn't exist any more.

3
votes

You can use saveAll() function, but you need to change the format of the GroupsUser array. According to documentation of saveAll() your data should look like this:

Array
     (
[Group] => Array
    (
        [name] => seyufgsduifsj
        [access] => 2
        [founder_id] => 3
        [random_key] => I6XC7uMTelpTSdq8DbtLPjqubiF7s6Pn
    )

[GroupsUser] => Array
    (
        [0] => Array
            (
               [user_id] => 3
               [group_role_id] => 1
               [random_key] => PZsDZXcoCTHw1IuvqsfURVpPX6AcZ3r2
            )
    )
)

Your example would work if the relation is Group belongsTo GroupsUser, but I believe this is not your case