cakephpので以下の様な多対多のデータベースを扱うプログラムを作成していますが,データが保存されず,困っています.
post モデルと test モデルを多対多で結合
addでは post側からtestを参照し,幾つかのtestをラジオボタンで選択出来るようにしたいです.
その際にposts_testsにpost_id と test_idを保存したいと考えていますが,うまく行きません.
どうやらHABTMの場合はformから返されるデータ配列の形式に気を付ける必要がわかりました.
参考URL:http://liginc.co.jp/programmer/archives/219
そして,formから返されるデータを確認出来るようにしました.
そこで質問です
恐らく以下に示す理想形のデータ形式にすることで解決できると考えたので,その様な形式でformデータを返す方法を教えて下さい.
以下にプログラムとformから返されるデータを載せます
php
1// PostsController.php 2<?php 3class PostsController extends AppController { 4public function add() { 5 6 if ($this->request->is('post')) { 7 $this->Post->create(); 8 9 if ($this->Post->save($this->request->data)) { 10 $this->set('redata',$this->request->data);//formから送信されたデータをビューに送る 11 12 13 $this->Session->setFlash(__('Your post has been saved.')); 14 15 //return $this->redirect(array('action' => 'index'));//確認作業の為にコメントアウト中 16 } 17 $this->Session->setFlash(__('Unable to add your post.')); 18 } 19 20 $this->set('tests',$this->Post->Test->find('list',array( 'fields'=>('Test.name')))); 21 $this->set('posts',$this->Post->find('all')); 22 } 23}?>
php
1// view add.ctp 2echo $this->Form->create('Post', array('class' => 'form-horizontal')); 3echo $this->Form->input('title'); 4echo $this->Form->input('test',array( 5 'label'=>false, 6 'multiple'=>'checkbox', 7 'legend' => false, 8 'div' => array('class' => 'controls radio'),)); 9 10echo $this->Form->button('登録', array('class' => 'btn btn-success')); 11?> 12 13<pre>redata 14<?php print_r($redata); ?> 15</pre>
php
1//Post Model Post.php 2public $hasAndBelongsToMany = array( 3 'Test' => 4 array( 5 'className' => 'Test', 6 'joinTable' => 'posts_tests', 7 'foreignKey' => 'post_id', 8 'associationForeignKey' => 'test_id', 9 'unique' => true, 10 'conditions' => '', 11 'fields' => '', 12 'order' => '', 13 'limit' => '', 14 'offset' => '', 15 'finderQuery' => '', 16 //'with' => '' 17 ), 18 );
現在のformで返される配列
Array ( [Post] => Array ( [title] => a [test] => Array ( [0] => 2 ) ) )
おそらく理想形と思われる配列(今は上の様な結果なので,下の様な配列にしたいと考えている)
Array ( [Post] => Array ( [title] => a ) [test] => Array ( [0] => 2 ) )
どんなことでも構いませんので,回答をよろしくお願いいたします.
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。