在cakephp中更新多个表

时间:2017-05-04 15:35:15

标签: php mysql cakephp cakephp-3.0

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用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.'));
    }

同时验证您承包商模型是否具有此定义的关联

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

希望这会有所帮助:)