yii\db\Migration::addForeignKey PHP Method

addForeignKey() public method

The method will properly quote the table and column names.
public addForeignKey ( string $name, string $table, string | array $columns, string $refTable, string | array $refColumns, string $delete = null, string $update = null )
$name string the name of the foreign key constraint.
$table string the table that the foreign key constraint will be added to.
$columns string | array the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array.
$refTable string the table that the foreign key references to.
$refColumns string | array the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
$delete string the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
$update string the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
    public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
    {
        echo "    > add foreign key {$name}: {$table} (" . implode(',', (array) $columns) . ") references {$refTable} (" . implode(',', (array) $refColumns) . ') ...';
        $time = microtime(true);
        $this->db->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
        echo ' done (time: ' . sprintf('%.3f', microtime(true) - $time) . "s)\n";
    }

Usage Example

 public function install()
 {
     parent::install();
     $migration = new Migration();
     $migration->createTable($this->getTable(), ['id' => Schema::TYPE_PK, 'object_id' => Schema::TYPE_INTEGER, 'term_id' => Schema::TYPE_BIGINT, 'value' => Schema::TYPE_STRING]);
     if ($migration->db->driverName === 'mysql') {
         $migration->addForeignKey('fk_' . $this->getTable() . '_' . $this->getRefTableName(), $this->getTable(), 'object_id', $this->getRefTableName(), 'id', 'CASCADE');
         $migration->addForeignKey('fk_' . $this->getTable() . '_' . TaxonomyTerms::tableName(), $this->getTable(), 'term_id', TaxonomyTerms::tableName(), 'id', 'CASCADE');
     }
 }
All Usage Examples Of yii\db\Migration::addForeignKey