Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add foreign key in Codeigniter migration

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?

like image 645
bumblebee Avatar asked Jul 05 '15 03:07

bumblebee


2 Answers

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)',
]);
like image 80
colonelclick Avatar answered Oct 23 '22 15:10

colonelclick


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

like image 3
Gpak Avatar answered Oct 23 '22 15:10

Gpak