CakePHP 2.4-如何在编辑之前在其他模型中保存数据副本?

CakePHP 2.4-如何在编辑之前在其他模型中保存数据副本?,cakephp,copy,edit,archive,Cakephp,Copy,Edit,Archive,我有两个简单的模型: 条目 身份证 头衔 内容 用户id 类别识别码 及 存档 身份证 头衔 内容 理由 用户id 类别识别码 入口id 我想问一下,在编辑条目之前,如何将条目的副本保存为存档,并添加编辑原因?我想把它作为CakePHP中最正确的方法 这将是将数据添加到存档模型(编辑条目)的唯一方法 我是否应该只在条目中包含归档模型,在编辑函数中只创建()归档,从条目中复制数据,从编辑表单中手动添加原因,并在编辑完成时保存() 我只在编辑时需要此功能。其他操作将是标准操作。修改您的请求数

我有两个简单的模型:

条目

  • 身份证
  • 头衔
  • 内容
  • 用户id
  • 类别识别码

存档

  • 身份证
  • 头衔
  • 内容
  • 理由
  • 用户id
  • 类别识别码
  • 入口id
我想问一下,在编辑条目之前,如何将条目的副本保存为存档,并添加编辑原因?我想把它作为CakePHP中最正确的方法

这将是将数据添加到存档模型(编辑条目)的唯一方法

我是否应该只在条目中包含归档模型,在编辑函数中只创建()归档,从条目中复制数据,从编辑表单中手动添加原因,并在编辑完成时保存()


我只在编辑时需要此功能。其他操作将是标准操作。

修改您的请求数据,如下所示:

$this->request->data['Archive'] = $this->request->data['Entry']
$this->request->data['Archive']['entry_id'] = $this->request->data['Entry']['id']
unset($this->request->data['Archive']['id']); // don't need this for archives

这样,请求中既有存档数据,也有条目数据。您可以在条目编辑表单中包含编辑原因。因为条目中没有字段有原因。。它不会被拯救。同时考虑使用该方法,它将同时处理保存/更新。此代码未经测试,但将是一个良好的开端

第六点-谢谢。你的回答真的帮助了我

我在代码中做了一些更改,下面是EntriesController中管理编辑功能的一部分:

if ($this->request->is(array('post', 'put'))) {

        //Load archive model and create object
        $this->loadModel('Archive');
        $this->Archive->create();

        //Geting data of current entry (yes, i want to save old, non-edited entry data in archives)
        $options = array('conditions' => array('Entry.' . $this->Entry->primaryKey => $id));
        $current_entry = $this->Entry->find('first', $options);

        //assignment to request data of archive
        $this->request->data['Archive'] = $current_entry['Entry'];

        //adding id for foregin key
        $this->request->data['Archive']['entry_id'] = $this->request->data['Entry']['id'];
        //adding reason from form data
        $this->request->data['Archive']['reason'] = $this->request->data['Entry']['reason'];
        //remove id, new entry of archive will be added
        unset($this->request->data['Archive']['id']);

        // save archive
        if ($this->Archive->save($this->request->data)) {
            $this->Session->setFlash(__('The archive has been saved.'));
        } else {
            $this->Session->setFlash(__('The archive could not be saved. Please, try again.'));
        }

        // save edited entry
        if ($this->Entry->save($this->request->data)) {
            $this->Session->setFlash(__('The entry has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The entry could not be saved. Please, try again.'));
        }
    }

现在我有我需要的了。我正在使用旧的(编辑前)条目数据,并合理地将其保存为存档。

您尝试了什么?请发布您尝试的解决方案,并告诉我们哪些不起作用