Using saveAll to save model that has multiple levels of hasMany (hasAndBelongsToMany) relationship with CakePHP 1.3

It turned out CakePHP failed to link GroupSet and Groups. No go…..

For example, GroupSet hasMany Groups and Group hasAndBelongsToMany users. They can be saved using one saveAll call. No need to deal with the IDs.

One level hasMany saveAll looks like:

Array
(
    [GroupSet] => Array
        (
            [name] => "Title"
        )
    [Group] => Array
        (
            [0] => Array
                (
                    [name] => On Gwoo the Kungwoo
                )
            [1] => Array
                (
                    [name] => More on Gwoo
                )
        )
)

The multiple levels hasMany (or HABTM) should looks like this:

Array
(
    [GroupSet] => Array
        (
            [name] => "Title"
        )
    [Group] => Array
        (
            [0] => Array
                (
                    [Group] => Array
                             (
                              [name] => Group1
                             )
                    [GroupMember] => Array
                       (
                          [0] => Array
                              (
                                [user_id] => 1
                              )
                          [1] => Array
                              (
                                [user_id] => 2
                              )
         )
         [1] => Array
                (
                    [Group] => Array
                             (
                              [name] => Group2
                             )
                    [GroupMember] => Array
                       (
                          [0] => Array
                              (
                                [user_id] => 3
                              )
                          [1] => Array
                              (
                                [user_id] => 4
                              )
                        )
                )
 )

Leave a Reply

Your email address will not be published. Required fields are marked *