我有一个视图/ vendor / add.ctp,其中包含两个关联表中的字段:供应商和地址。我能够同时保存两个表中的数据,但如果我尝试更新记录,它会创建数据库中的新行而不是更新它。
我正在搜索cakephp文档和Google上几个小时!但是找不到任何可以帮助我的东西。
供应商模型协会:
public $hasMany = array(
'Address' => array(
'className' => 'Address',
'foreignKey' => 'vendor_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
地址模型关联:
public $belongsTo = array(
'Vendor' => array(
'className' => 'Vendor',
'foreignKey' => 'vendor_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
这是我的VendorsController“编辑”动作
public function edit($id = null) {
if (!$this->Vendor->exists($id)) {
throw new NotFoundException(__('Invalid vendor'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->Vendor->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The vendor has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The vendor could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('Vendor.' . $this->Vendor->primaryKey => $id));
$this->request->data = $this->Vendor->find('first', $options);
}
$categories = $this->Vendor->Category->find('list');
$this->set(compact('categories'));
}
拜托,我需要帮助。 谢谢!
答案 0 :(得分:0)
您的Vendor
模型未收到要保存的行的id
,因此在您保存数据时会创建一个新模型。
您需要更改此行:
...
if ($this->Vendor->saveAssociated($this->request->data)) {
...
到此:
...
$this->Vendor->id = $id;
if ($this->Vendor->saveAssociated($this->request->data)) {
...