2016-01-06 21 views
5

Sto avendo due tabelle. Il mio tavolo principale è Studenti. E il mio tavolo secondario è esami. Sto provando a salvare entrambe le tabelle usando hasMany e appartiene a Mamma Associazione. Ma sta salvando i dati nella tabella Student solo, non in esami. Qualcuno può aiutarmi a risolvere questo problema.Salvataggio di molti dati di associazioni in CakePHP 3.x

studenti modello:

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']); 
    } 
} 

Esami Modello:

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']); 
    } 
} 

mio 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(); 

Nel mio 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.')); 
    } 
    } 
} 
+0

Qual è l'output di ** $ studente-> getErrors() ** dopo l'applicazione dell'entità. – styks

risposta

0

Patching BelongsToMany Associations

È necessario assicurarsi di essere in grado di impostare gli esami. Impostare accessibleFields per consentire di patchare i dati associati

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

È anche possibile fare questo con la proprietà _accessible $ nell'entità.

Problemi correlati