我想知道这个函数有什么问题,我只需要更新表中的一个字段或多关联表中的所有字段。 多更新工作正常,但是当我只更新第一列时,它对我来说工作不正常
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 获取关联的模型数据.
调整后你的代码将是这样的
$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/