jepster
(4004ar)
August 14, 2015, 7:53am
1
Hi,
I’ve googled and read the migration part from the yii guide, but I couldn’t find anything about defining foreign/primary key constraints for the migrations. Can anybody show me a example migration to define the foreign/primary key constraints?
Cheers
Hi,
Sorry, no offense, maybe I misunderstood your question.
But if I understand your question correctly I just HAVE to say that:
Your google skills must be very VERY bad…
Nearly ALL pages show how to do it.
But here is an example:
use yii\db\Schema;
use yii\db\Migration;
class m150520_074522_init_tbl_example extends Migration
{
public function up()
{
# SET TABLE OPTIONS / NAME
$tableName = 'my_example_table';
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
# CREATE TABLE
$this->createTable($tableName, [
// primary key of this table
'id' => Schema::TYPE_PK,
// FK to user_table
'user_id' => Schema::TYPE_INTEGER . ' NOT NULL',
'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
], $tableOptions
);
# ADD FOREIGN_KEY
# FROM my_example_table.user_id TO user_table.id
$this->addForeignKey('FK_example_to_user', $tableName, 'user_id', 'user_table', 'id', 'CASCADE','CASCADE');
# create unique index if needed
$this->createIndex('UNIQ_IDX_FK_example_to_user', $tableName, 'user_id', true);
}
public function down()
{
# DROP TABLE
$this->dropTable('cusmada_user_setting');
}
}
Hope this helps.
Regards
aisogroup
(E Poremchuk)
August 14, 2015, 1:45pm
3
Easy
Add to your migrate UP
section something like this:
$this->addForeignKey('FK_post_to_user', $tableName, 'userid', 'user', 'id', 'CASCADE','CASCADE');
where ‘userid’ - is you column with users id’s, ‘user’ - is reference table and ‘id’(primary key) - is column with id in reference table.
Enjoy it!