0

Hi Im just wondering if it is possible to save multiple data that has hasMany: and if it is possible what is the array structure before executing $this->Model->saveAll($this->data).

example is that you are going to save multiple posts at a time like this:

array(
    [Post] => Array
    (
        [0] => Array
            (
                [title] => title One
                [content] => desc One
            )

        [1] => Array
            (
                [title] => title two
                [content] => desc two
            )

    )

So in the given array above we can save all the Post with saveAll but what if each Post have hasMany comment each. how the array should look like if i have to insert the array below:

array(
    [Comment] => Array
    (
        [0] => Array
            (
                [comment] => 1st Comment for Post One
            )


        [1] => Array
            (
                [comment] => 2nd Comment for Post One
            )


        [2] => Array
            (
                [comment] => 1st Comment for Post Two
            )


        [3] => Array
            (
                [comment] => 2nd Comment for Post Two
            )

    )

How can I combine the two array to execute saveAll(); Thanks in advance. ^_^

1 Answer 1

2

Assuming the association for "post has many comments" is called "Comments", the data would look something like

array(
    'Post' => array(
        array(
            'title' => 'title1',
            'content' => 'content1',
            'Comments' => array(
                array('comment'=>'1st comment for post 1'),
                array('comment'=>'2nd comment for post 1'),
            ),
        array(
            'title' => 'title2',
            'content' => 'content2',
            'Comments' => array(
                array('comment'=>'1st comment for post 2'),
                array('comment'=>'2nd comment for post 2'),
            ),
        ),
    ),
)

To save you could use something like:

$this->Model->saveMany($data, array('deep'=>TRUE));

Note that the "deep" option requires CakePHP 2.1. Without it the associated Comment records would not be saved.

All this is documented in http://book.cakephp.org/2.0/en/models/saving-your-data.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.