add foreign key in Codeigniter migration add foreign key in Codeigniter migration codeigniter codeigniter

add foreign key in Codeigniter migration


Here are two ways to do that. The first works with create_table and the other can be done when adding a field to an existing 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)',]);


You could write a normal SQL Query to do that after

$this->dbforge->create_table('pelayanan');

See example below

$this->db->query('ALTER TABLE `pelayanan` ADD FOREIGN KEY(`ID_AREA`) REFERENCES 'the_other_table_name'(`ID_AREA`) ON DELETE CASCADE ON UPDATE CASCADE;');

You can do the same for the other foreign key


Someone created a way to do it here: https://github.com/bcit-ci/CodeIgniter/issues/1762. Unfortunately as of right now you still can't do it with out-of-the-box codeigniter. @Godluck's way works pretty well too.