Yii2のDB Migration最終回!
最後はデータのinsertを行います。
データを1つずつinsertしてもいいんですが、
通常1つだけデータをinsertするってことはないので、
初めからBatch Insertを行います。
通常のSQLでいうバルクインサートです。
記述方法は
$columns = array('id', 'title', 'content', 'sub_table_id' ); $values = array( array(1, 'Title1', 'これは1つ目', 1, ), array(2, 'Title2', 'これは2つ目', 1, ), ); $this->batchInsert('tablename', $columns, $values);
をその2で作成したファイルに追記
<?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'); //データinsert $columns = array('id', 'title', 'content', 'sub_table_id' ); $values = array( array(1, 'Title1', 'これは1つ目', 1, ), array(2, 'Title2', 'これは2つ目', 1, ), ); $this->batchInsert('tablename', $columns, $values); } public function down() { $this->dropTable('tablename'); } }
これで初期テーブル作成コマンド用のファイルの準備が完了しました。
あとは下記を実行すると・・・
yii migrate/to m150620_123401_create_tablename_table
テーブルが作成されて、外部キー制約、インデックス、データまで準備されちゃてます!
しかも、このファイルでDB作成用のSQLは不要!
いやー便利便利。