1

1 つのフォームで 2 つのテーブルのデータを更新したいのですが、データは 1 つのテーブルでのみ更新され、既存のレコードを更新する代わりに 2 番目のテーブルに挿入されます。これが私のコードです--

ファイルを閲覧する:

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 に答える