I want to add a new record in a table called TutorsSubject. This table is created from HABTM relationship of Tutor and Subject. Anyway I load the subject names in a text box and I can select a subject name but I cant add a new record. I need to set the id of the tutor_id. There are 3 fields in the tutorsSubject table called id,tutor_id and subject_id. I only need to select in 1 field which is the subject_id from a list of names found in the subject table, and then set the tutor_id manually.
Currently I am able to select from a list of subject names but I cant add a new record with the subject name and set tutor_id.
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
class TutorsSubjectsController extends AppController {
public function tutoradd() {
$this->loadModel('Subject');
$options['recursive']=-1;
$options['fields']=array('Subject.name');
$te2= $this->Subject->find('list',$options);
debug($te2);
$this->set( 'te',$te2);
//put is for edit and post for new record
if ($this->request->is('post')) {
$this->request->data['TutorsSubject']['tutor_id']=2;
debug($this->request->data);
if ($this->TutorsSubject->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('controller' => 'tutors','action' => 'tutordetails'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
//View which works fine as it displays the list
echo $this->Form->create('TutorsSubject', array('type' => 'post'));
echo $this->Form->input('tutorsSubject.subject_id', array('options' => $te));
echo $this->Form->end('Save Post');
//model subject
public $hasAndBelongsToMany = array(
'Tutor' => array(
'className' => 'Tutor',
'joinTable' => 'tutors_subjects',
'foreignKey' => 'subject_id',
'associationForeignKey' => 'tutor_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
//model tutor
public $hasAndBelongsToMany = array(
'Subject' => array(
'className' => 'Subject',
'joinTable' => 'tutors_subjects',
'foreignKey' => 'tutor_id',
'associationForeignKey' => 'subject_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
);