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');

控制器文件:

$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;
}
4

1 回答 1

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()方法可以正常工作。

现在发布它,看看我确信它现在可以工作。

干杯。

于 2013-02-26T12:41:37.377 回答