【问题标题】:cakephp 3 how to create new record from existing entitycakephp 3 如何从现有实体创建新记录
【发布时间】:2015-09-21 03:46:18
【问题描述】:

我有一个包含相关数据的实体,我想将其保存在新记录中。

我试试看:

$newTour = $this->Tours->get($id, ['contain' => ['Cities', 'Tags']]);
$newTour->set('id', null);
$this->Tours->save($newTour);

但是我看到了这个错误:

更新需要所有主键值

我该怎么办?

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    通过get()find() 检索到的实体将被设置为非新的,这会导致它们在保存时进入更新过程而不是插入过程。

    如果要将它们作为新记录插入,则必须将它们标记为新记录,此外还要取消设置主键。

    // ...
    $newTour->isNew(true);
    $newTour->unsetProperty('id');
    // ...
    

    另见

    【讨论】:

      【解决方案2】:

      使用$newTour->unsetProperty('id');取消设置属性,而不是$newTour->set('id', null);

      【讨论】:

        【解决方案3】:

        一个重要的细节,当我们有关联的表时,加载了

        ->contain() 选项

        ,我们需要对每个递归执行相同的操作,例如:

         $newTour->isNew(true);
         $newTour->unsetProperty('id');
         $newTour->other_table->isNew(true);
         $newTour->other_table->unsetProperty('id');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 2018-03-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多