我试图知道这个函数有什么问题,我需要只更新表中的一个字段或多个关联表中的所有字段。 多次更新工作正常,但是当我只更新第一列时它对我不起作用
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');
}
答案 0 :(得分:0)
您可以使用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'
]);
希望这会有所帮助:)