2014-12-22 3 views
0

У меня есть view/vendor/add.ctp с полями из двух связанных таблиц: Поставщики и Адреса. Я могу одновременно сохранять данные в обеих таблицах, но если я попытаюсь обновить запись, она создаст новую строку в базе данных, а не обновит ее.CakePHP 2.5.5 обновление связанных моделей has_many и ownedst_to

Я ищу документацию на cakephp и в Google часах! но не может найти ничего, что помогло бы мне.

Ассоциация по Vendor Модель:

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

Ваша Vendor модель не принимает id строки, которую нужно сохранить, и поэтому она создает новый при сохранении ваших данных.

Вы должны изменить эту строку:

 ... 
     if ($this->Vendor->saveAssociated($this->request->data)) { 
     ... 

к этому:

 ... 
     $this->Vendor->id = $id; 
     if ($this->Vendor->saveAssociated($this->request->data)) { 
     ...