Yii2のDB Migrationを使ってテーブル作成 その2 -index,外部キー制約-

Yii2のDB Migrationのその2。
今回はindexの貼り方、外部キー制約の設定、データ投入を行う。
前回の記事で作成した
m150620_123401_create_tablename_table.phpというファイルを触っていきます。

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150620_123401_create_tablename_table extends Migration
{
    public function up()
    {
        $this->createTable('tablename', [
            'id' => Schema::TYPE_PK,
            'title' => Schema::TYPE_STRING . ' NOT NULL',
            'content' => Schema::TYPE_TEXT,
            'sub_table_id' => Schema::TYPE_INTEGER,
        ]);
    }

    public function down()
    {
        $this->dropTable('tablename');
    }
}

現在は上記のようにテーブルの作成と削除だけが設定されています。
まずは外部キー制約の設定を行います。
外部キー制約で使うカラムsub_table_idを追加しています。
今回の例ではsub_tableのidを対象に設定します。

$this->addForeignKey('fkey_tablename_sub_table_id', 'tablename', 'sub_table_id', 'sub_table','id');

外部制約キーの名前(任意)、自身のテーブル名、自身のカラム、制約対象テーブル名、制約対象カラムの順に記載します。
この一文をcreateTableの下に追記します。

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150620_123401_create_tablename_table extends Migration
{
    public function up()
    {
        $this->createTable('tablename', [
            'id' => Schema::TYPE_PK,
            'title' => Schema::TYPE_STRING . ' NOT NULL',
            'content' => Schema::TYPE_TEXT,
            'sub_table_id' => Schema::TYPE_INTEGER,
        ]);
        $this->addForeignKey('fkey_tablename_sub_table_id', 'sub_table', 'sub_table_id', 'sub_table','id');
    }

    public function down()
    {
        $this->dropTable('tablename');
    }
}

次にtitleにindexを貼ってみましょう。

$this->createIndex('tablename_title_index', 'tablename', 'title');

indexの名前(任意)、テーブル名、対象のカラムの順に記載します。
この一文をcreateTableの下に追記します。

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150620_123401_create_tablename_table extends Migration
{
    public function up()
    {
        $this->createTable('tablename', [
            'id' => Schema::TYPE_PK,
            'title' => Schema::TYPE_STRING . ' NOT NULL',
            'content' => Schema::TYPE_TEXT,
            'sub_table_id' => Schema::TYPE_INTEGER,
        ]);
        $this->addForeignKey('fkey_tablename_sub_table_id', 'sub_table', 'sub_table_id', 'sub_table','id');
        $this->createIndex('tablename_title_index', 'tablename', 'title');
    }

    public function down()
    {
        $this->dropTable('tablename');
    }
}

これでindexが作成されます。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA