无法在HABTM表中添加新记录

时间:2014-09-22 11:05:53

标签: php cakephp

我想在名为TutorsSubject的表中添加新记录。该表是根据Tutor和Subject的HABTM关系创建的。无论如何,我在一个文本框中加载主题名称,我可以选择一个主题名称但我不能添加一个新的记录。我需要设置tutor_id的id。 tutorsSubject表中有3个字段,名为id,tutor_id和subject_id。我只需要从主题表中找到的名称列表中选择1个字段作为subject_id,然后手动设置tutor_id。

目前,我可以从主题名称列表中进行选择,但我无法添加主题名称的新记录并设置tutor_id。

错误:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

class TutorsSubjectsController扩展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' => ''
        ),

    );

0 个答案:

没有答案