Is anybody can help me to add Foreign Key and in 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 Forein Key in this table. How can I resolve this?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With