cakePHP使用hasMany函数保存所有数据

时间:2012-03-27 14:36:28

标签: cakephp

嗨我只是想知道是否可以保存hasMany的多个数据:如果可能的话,在执行$ this-> Model-> saveAll($ this-> data)之前是什么是数组结构。

示例是您要一次保存多个帖子:

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

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

    )

所以在上面的给定数组中,我们可以使用saveAll保存所有Post,但是如果每个Post都有多个注释,那该怎么办呢。如果我必须在下面插入数组,数组应该如何:

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
            )

    )

如何组合两个数组来执行saveAll(); 提前致谢。 ^ _ ^

1 个答案:

答案 0 :(得分:2)

假设“帖子有很多评论”的关联称为"Comments",则数据看起来像

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'),
            ),
        ),
    ),
)

要保存,您可以使用以下内容:

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

请注意,“深度”选项需要CakePHP 2.1。没有它,相关的评论记录将不会被保存。

所有这些都记录在http://book.cakephp.org/2.0/en/models/saving-your-data.html

相关问题