php - 在cakephp中更新多表

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

最佳答案

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

希望这会有所帮助:)

关于php - 在cakephp中更新多表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43787261/

相关文章:

php - 限制子句上的sql注入(inject)

php - 同一患者的不同订单号只能让我从 DB 获取一份

php - cakephp 中的 requestAction

mysql - CakePHP 模型在 SQL 语句中使用了错误的字段!

php - 优化 mysql 设置/表以提高负载下的性能

PHP - 为什么读取这个 csv 文件使用这么多内存,我该如何改进我的代码?

Php/Mysql 简单调查

PHP:如何在主命名空间中导入子命名空间?

bash - 如何获取 php 结果并在 bash 中使用它?

php - 在 CakePHP 中将 Controller 渲染到不同的 View