用fk迁移Yii2

时间:2017-05-29 20:26:59

标签: php mysql database yii2 migration

我是Yii2框架中的新手。我开始学习这个...... 现在我尝试用FK制作2张桌子,但我无法理解。如果有人能说我怎么用FK看桌子,我会很高兴。

迁移一个:

 public function up()
{
    $this->createTable('portfolio', [
        'id' => $this->primaryKey(),
        'project_name'          => $this->string()->notNull(),
        'main_image'            => $this->string(),
        'galery'                => $this->string(),
        'link_to_live_project'  => $this->string()->notNull(),
        'short_description'     => $this->string(),
        'full_description'      => $this->string()->notNull(),
        'date_released'         => $this->string(),
        'technologies'          => $this->string()->notNull(),
        'created_at'            => $this->dateTime(),
    ]);
}

/**
 * @inheritdoc
 */
public function down()
{
    $this->dropTable('portfolio');
}

第二次迁移:

 public function up()
{
    $this->createTable('gallery_to_portfolio', [
        'id' => $this->primaryKey(),
    ]);
}

/**
 * @inheritdoc
 */
public function down()
{
    $this->dropTable('gallery_to_portfolio');
}

我想在第二次迁移中做fk。

1 个答案:

答案 0 :(得分:1)

第二次迁移功能的代码应如下所示:

 $this->createTable('gallery_to_portfolio', [
        'id' => $this->primaryKey(),
        'portfolioId' => $this->integer()->notNull(),
        ... other fields ...
    ]);

$this->addForeignKey('fk-gallery_to_portfolio-portfolio','gallery_to_portfolio','portfolioId','portfolio','id','cascade');