【问题标题】:CakePHP 2.4 - how to save copy of data in other model before edit?CakePHP 2.4 - 如何在编辑前将数据副本保存在其他模型中?
【发布时间】:2013-11-29 03:38:54
【问题描述】:

我有 2 个简单的模型:

参赛作品

  • 身份证
  • 标题
  • 内容
  • user_id
  • category_id

存档

  • 身份证
  • 标题
  • 内容
  • 原因
  • user_id
  • category_id
  • entry_id

我想问一下如何在编辑之前将条目的副本保存为存档并添加编辑原因?我想把它作为 CakePHP 中最正确的方式来做。

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

我应该只在 Entry 中包含 Archive 模型,在编辑函数中只需 create() Archive,从 Entry 复制数据,手动添加编辑表单的原因和 save() 何时完成编辑?

我只有在编辑时才需要这个功能。其他操作将是标准的。

【问题讨论】:

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

标签: cakephp copy edit archive


【解决方案1】:

第六点 - 谢谢。你的回答对我很有帮助。

我对我的代码进行了一些更改,这是我在 EntriesController 中的 admin_edit 函数的一部分:

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.'));
        }
    }

现在我得到了我需要的东西。我变老了(编辑前)条目数据并将其保存为存档。

【讨论】:

    【解决方案2】:

    像这样修改您的请求数据:

    $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
    

    这样,请求中同时包含存档和条目数据。您可以在您的条目编辑表单中包含编辑原因。由于条目中没有任何字段有原因..它不会被保存。还要考虑使用saveAll 方法,它会同时处理保存/更新。此代码未经测试,但将是一个好的开始

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多