I have two tables. My main table is students. And my secondary table is exams. I am trying to save both tables using hasMany and attribToMany . But it only stores data in the Student table, not in exams. Can anyone help me solve this problem.
Student Model:
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']); } }
Exam Model:
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']); } }
My 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();
In my controller:
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.')); } } }
source share