Add foreign key in Codeigniter migration

Can anyone help me add the foreign key and codeigniter migration database? This is the code:

public function up() { $this->dbforge->add_field(array( 'ID_PELAYANAN' => array( 'type' => 'INT', 'constraint' => 50, 'auto_increment' => TRUE ), 'THBLMUT' => array( 'type' => 'VARCHAR', 'constraint' => '6', ), 'ID_DIST' => array( 'type' => 'VARCHAR', 'constraint' => '2', ), 'ID_AREA' => array( 'type' => 'VARCHAR', 'constraint' => '5', ), 'ID_RAYON' => array( 'type' => 'VARCHAR', 'constraint' => '5', ), 'N_RAYON' => array( 'type' => 'CHAR', 'constraint' => '70', ), )); $this->dbforge->add_key('ID_PELAYANAN', TRUE); $this->dbforge->create_table('pelayanan'); } public function down() { $this->dbforge->drop_table('pelayanan'); } } 

I want to make 'ID_AREA', 'ID_RAYON' as the Forein Key in this table. How can i solve this?

+6
source share
3 answers

Here are two ways to do this. The first works with create_table, and the other can be done by 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)', ]); 
+5
source

You can write a regular SQL query to do this 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 another foreign key

+1
source

Someone created a way to do this here: https://github.com/bcit-ci/CodeIgniter/issues/1762 . Unfortunately, as of right now, you still cannot do this with ready-made code. @Godluck also works very well.

0
source

All Articles