【问题标题】:cakePHP saving All data with hasMany functioncakePHP 使用 hasMany 函数保存所有数据
【发布时间】:2012-03-27 14:36:27
【问题描述】:

您好,我只是想知道是否可以保存多个具有 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 保存所有的帖子,但是如果每个帖子都有 hasMany 评论怎么办。如果我必须在下面插入数组,数组应该是什么样子:

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(); 提前致谢。 ^_^

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    假设“post has many cmets”的关联称为"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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-10
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多