Search code examples
cakephpcakephp-2.0cakephp-2.3cakephp-2.1

What is the best way to Update/Add/Delete multiple records in the same form with CakePHP


I have this Topic table who is linked to the table Post with hasMany in the model.

This is my $this->request->data

Array
(
[Topic] => Array
    (
        [id] => 1
        [topic_title] => This is my topic
    )

[Post] => Array
    (
        [1] => Array
            (
                [id] => 1
                [title] => Blah
                [message] => My message
            )

        [2] => Array
            (
                [id] => 2
                [title] => Second Blah
                [message] => Second My message
            )

    )

)

And I update it with :

$this->Topic->saveAssociated($this->request->data);

But What if I also wanted to have the ability to add and delete posts to this topic, how would I proceed ?


Solution

  • Keeping the same structure, you could do a $this->Topic->saveAssociated($this->request->data); and it will add any new ('id' => NULL or unset) items in the data array.

    About the delete, the only case I know would delete at the same time, would be a HABTM when it's marked as 'unique' => true. Otherwise, you need to do a $this->Post->deleteAll(array('Post.topic_id' => $unwanted_topic_id), false);

    I could think of making a new array keeping the ones you want deleted and sending them as condition for the deleteAll function.