codeigniter迁移错误外键约束

时间:2017-10-24 13:02:24

标签: mysql codeigniter foreign-keys database-migration

我在我的CI中进行了迁移,现在我在制作一些外键时出错了。我如何制作一些外键,我在这里看到一些与此主题相关的问题,但它并没有解决我的问题。

这是我的代码,我收到错误:

public function up() {
         $this->dbforge->add_field(array(
            'student_id' => array(
                    'type' => 'INT',
                    'constraint' => 11,
                    'unsigned' => TRUE,
                    'auto_increment' => TRUE
            ),
            'course_id' => array(
                    'type' => 'INT',
                    'constraint' => 11,

            ),
            'fname' => array(
                    'type' => 'VARCHAR',
                    'constraint' => 50,                    
            ),
            'lname' => array (
                    'type' => 'VARCHAR',
                    'constraint' => 50,
            ),
            'gender' => array (
                    'type' => 'VARCHAR',
                    'constraint' => 1
            ),
            'bday' => array (
                    'type' => 'DATE'                    
            )
        ));
        $this->dbforge->add_key('student_id', TRUE);
        $this->dbforge->add_field('CONSTRAINT FOREIGN KEY (course_id) REFERENCES tbl_course(id)');
        $this->dbforge->create_table('tbl_students');

它给我一个错误:

 Can't create table `student_db`.`tbl_students` (errno: 150 "Foreign key constraint is incorrectly formed")

CONSTRAINT FOREIGN KEY (course_id) REFERENCES tbl_course(id),
        CONSTRAINT `pk_tbl_students` PRIMARY KEY(`student_id`)
) DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci

1 个答案:

答案 0 :(得分:0)

您需要运行

dbforge->add_key    

之前的

dbforge->create_table

这样的事情:

$this->dbforge->add_field('CONSTRAINT FOREIGN KEY (id) REFERENCES table(id)');

$this->dbforge->add_column('table',[
    'CONSTRAINT fk_id FOREIGN KEY(id) REFERENCES table(id)',
]);