2016-01-06 31 views
5

私は2つのテーブルを持っています。私のプライマリテーブルは生徒です。私の副表は試験です。私はを使用して両方のテーブルを保存しようとしています。hasManybelongsToMany Association。しかし、それは学生の表にのみ、試験ではないデータを保存しています。この問題を解決するのに助けてくれる人がいますか?HasMany関連を保存するCakePHP 3.xのデータ

学生モデル:

class StudentsTable extends Table { 
    public function initialize(array $config) { 
    $this->addBehavior('Timestamp'); 
    parent::initialize($config); 
    $this->table('students'); 
    $this->primaryKey(['id']); 
    $this->hasMany('Exams', [ 
     'className' => 'Exams', 
     'foreignKey' => 'student_id', 
     'dependent'=>'true', 
     'cascadeCallbacks'=>'true']); 
    } 
} 

試験モデル:

class ExamsTable extends Table { 
    public function initialize(array $config) { 
    parent::initialize($config); 
    $this->table('exams'); 
    $this->primaryKey(['id']); 
    $this->belongsToMany('Students',[ 
     'className'=>'Students', 
     'foreignKey' => 'subject_id', 
     'dependent'=>'true', 
     'cascadeCallbacks'=>'true']); 
    } 
} 

マイschool.ctp:私のコントローラで

echo $this->Form->create(); 
echo $this->Form->input('name'); 
echo $this->Form->input('exams.subject', array(
    'required'=>false, 
    'multiple' => 'checkbox', 
    'options' => array(
    0 => 'Tamil', 
    1 => 'English', 
    2 => 'Maths'))); 
echo $this->Form->button(__('Save')); 
echo $this->Form->end(); 

public function school() { 
    $this->loadModel('Students'); 
    $this->loadModel('Exams'); 
    $student = $this->Students->newEntity(); 
    if ($this->request->is('post')) { 
    $this->request->data['exams']['subject'] = 
     implode(',',$this->request->data['exams']['subject']); 
    $student = $this->Students->patchEntity(
     $student, $this->request->data, ['associated' => ['Exams']] 
    ); 
    if ($this->Students->save($student)) { 
     $this->Flash->success(__('The user has been saved.')); 
    } else { 
     $this->Flash->error(__('Unable to add the user.')); 
    } 
    } 
} 
+0

エンティティにパッチを当てた後の** $ student-> getErrors()**の出力は何ですか? – styks

答えて

0

Patching BelongsToMany Associations

試験を設定できることを確認する必要があります。セットaccessibleFieldsはあなたがまた、エンティティ内の$ _accessibleプロパティでこれを行うことができ、関連するデータ

$student = $this->Students->patchEntity(
    $student, $this->request->data, [ 
     'associated' => ['Exams'], 
     'accessibleFields' => ['exams' => true] 
    ] 
); 

にパッチを適用することができるようにします。

関連する問題