1

i made a migration in my CI, now i have error in making some foreign key in it. How can i make some foreign key, i saw some questions here related to this topic but it doesn't solve my problem.

Here is my code where i got error:

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

it gives me an error of :

 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
Jc John
  • 1,799
  • 2
  • 34
  • 69
  • did you check if the foreign key column and the referencing column are the same type or length? – Vickel Oct 24 '17 at 13:43
  • @Vickel do i need to make them thesame? thanks for fast reply – Jc John Oct 24 '17 at 13:54
  • @Vickel hello sir. yes. i checked it, and its the same. here is it. 'id' => array( 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ), – Jc John Oct 24 '17 at 13:55
  • run through this post, you might find what you need: https://stackoverflow.com/questions/8434518/mysql-foreign-key-constraint-is-incorrectly-formed-error – Vickel Oct 24 '17 at 13:56
  • @Vickel its already the-same data type – Jc John Oct 24 '17 at 14:05

1 Answers1

0

You needed to run the

dbforge->add_key    

before the

dbforge->create_table

Something like this:

$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)',
]);
always-a-learner
  • 3,671
  • 10
  • 41
  • 81