【问题标题】:update multi tables in cakephp更新 cakephp 中的多个表
【发布时间】:2017-05-04 15:35:15
【问题描述】:

我想知道这个函数有什么问题,我只需要更新表中的一个字段或多个关联表中的所有字段。 多重更新工作正常,但是当我只更新第一列时,它对我来说不能正常工作

public function edit($id) {
    $contractor = $this->Contractors->get($id);

     $associated = ['ContractorsAttachments' ];
    // Used to get the all attachments associated with Contractors 
     $ContractorsAttachments = $this->Contractors->ContractorsAttachments->find()->where(['contractor_id' => $id])->all();
    if ($this->request->is(['patch', 'post', 'put'])) {
      $contractor = $this->Contractors->patchEntity($contractor, $this->request->data );

       if ($this->Contractors->save($contractor)) {

            $this->Flash->success(__('The Contractors has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The Contractors could not be saved. Please, try again.'));
    }
    $this->set(compact('contractor','ContractorsAttachments'));
    $this->set('_serialize', ['contractor']);
    $this->render('add');
    }

【问题讨论】:

  • $associated = ['ContractorsAttachments' ]有什么用

标签: php mysql cakephp cakephp-3.0


【解决方案1】:

您可以使用contain 获取关联的模型数据。

使用Saving With Associations

调整后你的代码会是这样的

     $contractor = $this->Contractors->get($id, ['contain'=>'ContractorsAttachments']);

     if ($this->request->is(['patch', 'post', 'put'])) {
       $contractor = $this->Contractors->patchEntity($contractor, $this->request->data );

       if ($this->Contractors->save($contractor,['associated' => ['ContractorsAttachments']])) {

            $this->Flash->success(__('The Contractors has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The Contractors could not be saved. Please, try again.'));
    }

同时验证您的 Contractors 模型具有这样定义的关联

        $this->hasMany('ContractorsAttachments', [
            'foreignKey' => 'contractor_id'
        ]);

希望这会有所帮助:)

【讨论】:

  • 谢谢你的评论,问题出在我的表单上,又回到了这一行 = $this->Form->create($contractor, ['type' => ' file']) ?> 你能知道如何使文件不需要吗?
猜你喜欢
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 2013-01-22
相关资源
最近更新 更多