2016-01-06 4 views
5

У меня есть две таблицы. Мой основной стол: Студенты. И мой дополнительный стол Экзамены. Я пытаюсь сохранить обе таблицы, используя hasMany и принадлежитToMany Ассоциация. Но он сохраняет данные в Студент таблица только, а не в Экзамены. Может ли кто-нибудь помочь мне решить эту проблему.Сохранение ассоциаций 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']); 
    } 
} 

Exams Модель:

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, чтобы позволить вам исправить связанные с ними данные

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

Вы также можете сделать это с _accessible свойством $ в сущности.

Смежные вопросы