Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save multiple records for one model in CakePHP

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?

like image 919
linkyndy Avatar asked Nov 23 '10 20:11

linkyndy


2 Answers

First off, this database design needs to be normalized.

It seems to me like a Notification can have many Users related to it. At the same time, a User can have many Notifications. Therefore,

  • Introduce a join table named users_notifications.
  • Implement the HABTM Relationship: Notification hasAndBelongsToMany User

In the view, you can simply use the following code to automagically bring up the multi-select form to grab user ids:

echo $this->Form->input('User');

The data that is sent to the controller will be of the form:

Array(
    [Notification] => Array
        (
            [subject] => subject
            [content] => contentcontentcontentcontentcontentcontent
        ),
    [User] => Array
        (
            [User] => Array
                (
                    [0] => 4
                    [1] => 6
                )
         )
)

Now, all you have to do is called the saveAll() function instead of save().

$this->Notification->saveAll($this->data);

And that's the Cake way to do it!

like image 118
RabidFire Avatar answered Nov 15 '22 11:11

RabidFire


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

like image 28
2 revs Avatar answered Nov 15 '22 10:11

2 revs