嘿伙计们请帮助我,我希望通过单个表单更新两个表数据,但数据只在一个表中更新并插入第二个表而不是更新现有记录。这是我的代码 -
查看文件:
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;
}
答案 0 :(得分: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()
方法正常工作。
现在发布它,看看我相信它现在会起作用。
干杯。