こんにちは、現在受講管理システムを作っています。
Cakephp3 のアソシエーションというものを使うと一括でできると聞いたのでマニュアルにそって試してみましたが、だめでした。POST値は正しく受け取っていますが、SaveMany()がTrueになるのにDBには何もInsertされていません。
TableはSubjectとsubject_equipment,subject_participantの3つで、DB上には関連キーは設定していません。
やりたいのは、1つのページのPOSTデータを分けて3つのテーブルに入れたいです。
SubjectTableでは以下のようにアソシエーションを設定しました。JoinTableも作りました。
Php
1class SubjectTable extends Table 2{ public function initialize(array $config) 3 { 4 parent::initialize($config); 5 6 $this->setTable('subject'); 7 $this->setDisplayField('subject_idx'); 8 $this->setPrimaryKey('subject_idx'); 9 10 $this->addBehavior('Timestamp'); 11 12 $this->belongsToMany('SubjectEquipment', ['foreignKey' => 'subject_idx', 'joinTable' => 'subject_equipment']); 13 $this->belongsToMany('SubjectParticipant', ['foreignKey' => 'subject_idx', 'joinTable' => 'subject_participant']); 14 15 }
add.ctpでは要素ごとに名前をつけておきました。データはちゃんと取れているので問題ないかと思います。
HTML
1 2<?= $this->Form->hidden('subject.subject_idx',['value' => 1]); ?> 3<?= $this->Form->multiCheckbox('subject_equipment.equipment_idx',$equipments)?> 4<?= $this->Form->control('subject_participant.participant_idx',['options' =>$participants, 'label'=>false, 'multiple' => true])?>
コントローラーに問題がありそうですがなかなか見つかりません。PatchEntityをPatchEntitiesにしたり、saveMany()をsave()に変えたりするとerrorのFlashメッセージが示されます。このコードでは、SuccessのFlashメッセージが表示されますがDBには何も起こりませんでした。
PHP
1 public function add() 2 { 3 $subject = $this->Subject->newEntity(); 4 5 if ($this->request->is('post')) { 6 $subject = $this->Subject->patchEntity($subject, $this->request->getData(),[ 7 'associated' => [ 8 'SubjectEquipment', 9 'SubjectParticipant', 10 ] 11 ]); 12 13 if ($this->Subject->saveMany($subject)) { 14 $this->Flash->success(__('The subject has been saved.')); 15 return $this->redirect(['action' => 'index']); 16 } 17 $this->Flash->error(__('The subject could not be saved. Please, try again.')); 18 } 19 $this->set(compact('subject')); 20 $this->set('_serialize', ['subject']);
アソシエーションがまだ理解できてないのもありますが、マニュアルが分かりにくく同じくしてみても動きませんでした。
どこか間違っているところがありましたら、教えていただけますでしょうか。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/16 04:56
2017/10/16 05:09 編集
2017/10/16 05:40
2017/10/16 09:04
2017/10/16 09:26
2017/10/16 10:19
2017/10/16 11:49
2017/10/16 11:54
2017/10/17 02:04
2017/10/17 03:04