2013-02-26 54 views
1

嘿傢伙請幫我在這我想更新兩個表的數據通過一個單一的表格,但數據更新只在一個表中,並插入第二個表中,而不是更新現有的記錄。這裏是我的代碼 -通過一個表單更新多個模型

查看文件:

echo $this->Form->create('Question'); 
echo $this->Form->input('question'); 
foreach (range(0,2) as $index) 
{ 
    echo $this->Form->input('Option.'.$index.'.poll_options'); 
} 
echo $this->Form->input('id',array('type'=>'hidden')); 
echo $this->Form->end('Save Poll'); 

Controller文件:

$data=$this->Question->findById($id); 
if($this->request->is('post') || $this->request->is('put')) 
{ 
    if($this->Question->saveAll($this->request->data)) 
    { 
     $this->Session->setFlash('Question has been updated'); 
     $this->redirect(array('action'=>'index')); 
    } 
    else 
    { 
     $this->Session->setFlash('Question has not been updated'); 
    } 
} 
if(!$this->request->data) 
{ 
    $this->request->data=$data; 
} 
+0

http://stackoverflow.com/questions/14831307/how-to-insert-multiple-records/14831717#14831717 – 2013-02-26 12:08:38

+0

這是代碼插入數據庫..我想更新字段,而不是添加... – Vicky 2013-02-26 12:11:06

+0

它不是在cakephp中的主要區別只是讀取數據和通過身份證在隱藏然後cakephp會爲你做更新...我看不到隱藏的ID創建你的 – 2013-02-26 12:12:29

回答

0

控制器代碼解釋。

<?php 
    $data = $this->Question->findById($id); 

以上將返回所有的問題,並如下文相關聯的答案陣列。

Array 
(
    [Question] => Array 
    (
     [id] => 121 
     [name] => Gwoo the Kungwoo 
     [created] => 2007-05-01 10:31:01 
    ) 
    [Option] => Array 
    (
     [0] => Array 
      (
       [id] => 123 
       [quesion_id] => 121 
       [body] => The Kungwooness is not so Gwooish 
       [created] => 2006-05-01 10:31:01 
      ) 
     [1] => Array 
      (
       [id] => 124 
       [quesion_id] => 121 
       [title] => More on Gwoo 
       [created] => 2006-05-01 10:41:01 
      ) 
    ) 
) 

現在,我們需要做的是建立我們的表(讓我們把很簡單的東西):

echo $form->create('Question', array('action' => 'edit')); 
foreach($this->data['Option'] as $key => $value) 
{ 
    echo $form->input('Option.'.$key.'.name'); 
    echo $form->input('Option.'.$key.'.id'); 
} 
echo $form->end('Save All'); 

它是由我們$this->data陣列建成並遵循完全正確的格式,這允許saveAll()方法正常工作。

現在發佈,看看我相信它現在可以工作。

乾杯。

+0

它沒有工作...仍然是同樣的事情正在發生... :( – Vicky 2013-02-26 12:52:15

+0

@ user1990503它會給你錯誤...必須工作,因爲它的唯一途徑...讓我知道你的模型代碼和之間的關聯他們 – 2013-02-26 12:53:28

+0

沒有錯... 有問題的模型文件...我申請了很多關係和在我申請的選項模型屬於關係... – Vicky 2013-02-26 12:54:48