Error On Adding Foreign Keys Using Migrate

I have created a migration using migrate create and put following codes on it:


<?php


class m131220_121449_create_all_tables extends CDbMigration

{   

    // Use safeUp/safeDown to do migration with transaction

    public function safeUp() {

        // MEMBERS TABLE

        $this->createTable("members", array(

            'uniq_id' => 'pk',

            'personel_num' => 'int(10) NOT NULL',

            'password' => 'string NOT NULL',

            'name' => 'string DEFAULT NULL',

            'lastupdate' => 'timestamp DEFAULT CURRENT_TIMESTAMP',

        ), 'ENGINE=InnoDB');


        // RESERVED TABLE

        $this->createTable("reserved", array(

                'uniq_id' => 'pk',

                'personel_num' => 'int(10) NOT NULL',

                'RsvdDay' => 'date NOT NULL',

                'date_created' => 'timestamp DEFAULT CURRENT_TIMESTAMP',

        ), 'ENGINE=InnoDB');


        // Add Foreign Keys Relations for RESERVED

        $this->addForeignKey("fk_rsvd_user", "reserved", "personel_num", "members", "personel_num", "CASCADE", "RESTRICT");

        }


}

But when I want to up this migration I got General Error #1005 when it tries to create Foreign Keys.

The image of the error has been attached.

Which DBMS are you using?

MySQL via WAMP on Windows 8.1

The answer was found:

The reference of a foreign key has to be a Primary Key in other table.

please help i have the same problem… what shuold be done?

I am also getting same error. when adding foreign key

$this->addForeignKey(‘FK_news’, ‘tbl_news’, ‘id’, ‘tbl_post’, ‘news_id’);

Id in tbl_news is Primary Key.

Your definition looks wrong.

Foreign key should be defined from post to news.

Yes you are right. Correct syntax is -

$this->addForeignKey(‘FK_news’, ‘tbl_post’, ‘news_id’, ‘tbl_news’, ‘id’);

Thanks :slight_smile: