【问题标题】:Can't update multiple records on tables with hasMany in CakePhp无法在 CakePhp 中使用 hasMany 更新表上的多条记录
【发布时间】:2016-10-18 14:18:21
【问题描述】:

我有一个表“主题”,它与模型中的 hasMany 链接到“帖子”。

我不知道如何同时更新这两个表。

这是我的 $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
              )

      )

)

我试过这样做:

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

$this->loadmodel('Post');

$this->Post->updateAll($this->request->data, array('Post.topic_id' => $id));

这显然是错误的方法,但是我努力寻找一种好的方法。

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.3 cakephp-2.1


    【解决方案1】:

    你应该使用 saveAssociated

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

    【讨论】:

      【解决方案2】:

      如果您使用$this->Topic->save($this->request->data),它只会尝试将 [Topic] 数组保存在您的数据数组中。

      您可以使用$this->Topic->saveAssociated($this->request->data)$this->Topic->saveAll($this->request->data) 将保存应用到数据数组中的其他数组。 saveAll() 函数涵盖了 saveAssociated()saveMany() 保存,尽管 cakePHP 手册建议使用其中之一而不是 saveAll() 函数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-04
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多