Save multiple records for one model in CakePHP

linkyndy picture linkyndy · Nov 23, 2010 · Viewed 19k times · Source

I would like to save several records for one model. This would have been done pretty easily with saveAll() if it hadn't been for a problem:

I have a notification form, where I select multiple users from a <select> and two fields, for subject and content respectively. Now, when I output what $this->data contains, I have:

Array([Notification] => Array
    (
        [user_id] => Array
            (
                [0] => 4
                [1] => 6
            )

        [subject] => subject
        [content] => the-content-here
    )
)

I've read on Cake 1.3 book, that in order to save multiple records for a model, you have to have the $this->data something like:

Array([Article] => Array(
        [0] => Array
            (
                        [title] => title 1
                    )
        [1] => Array
            (
                        [title] => title 2
                    )
            )
)

So, how do I 'share' the subject and content to all selected users?

Answer

Ish picture Ish · Nov 23, 2010

Those values have to be repeat like this

Array([Notification] => Array(
        [0] => Array
            (
                        [user_id] => 4
                        [subject] => subjects
                        [content] => content
                    )
        [1] => Array
            (
                        [user_id] => 6
                        [subject] => subject
                        [content] => contents
                    )
            )
)


$this->Notification->saveAll($data['Notification']); // should work

If you don't pass any column value, this cake will just ignore it