LarabelでのDB作成時に、migrateというものがあったので、使ってみました。
チームで全く同じDBをつかいたいときなどは、migratefileをそろえておくとまったくおなじDBがつかえます。
DB作成
CREATE DATABASE DB名;
マイグレーション生成
php artisan make:migration テーブル名
テーブル作成
new_hoge_table.php
public function up()
{
Schema::create('テーブル名', function (Blueprint $table) {
$table->increments('カラム名');//autoincrement主キー
$table->integer('カラム名')->unsigned();//int型つかえないのでmigrationの場合はinteger
$table->string('カラム名', 文字数)->default("")->unique();//ユニークの書き方はこんな感じ
$table->datetime('カラム名')->default(DB::raw('CURRENT_TIMESTAMP'));//デフォルトでINSERTした日付とってくる
$table->boolean('カラム名')->default(0);//true or false
// 外部キー
$table->foreign('外部キー')
->references('参照カラム')
->on('参照テーブル名');
});
}
public function down()
{
Schema::dropIfExists('テーブル名');
}
おまじない
外部キー設定がうまくいかなかったら意味もなくこれつけてみる
$table->engine = 'InnoDB';
※カラムに関してはよくわからないけど、使えない型があるので注意。intとか使えないみたいです。
新規データベースならば、上のupメソッドを修正する
しかし、リリース後のDB定義修正の場合は、直接修正するのではなく、新たにファイルを作成し、修正を記述
fix_hoge_table.php
public function up()
{
Schema::table('修正テーブル名', function (Blueprint $table) {
$table->boolean('maintenance_flag')->after('start_date')->default(0)->nullable(false);
$table->string('maintenance_message',40)->after('maintenance_flag')->nullable(true);
$table->string('maintenance_message', 255)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('修正したいテーブル', function (Blueprint $table) {
//追加したいカラム(修正はかかなくてもいいはず)
$table->dropColumn('maintenance_flag');
$table->dropColumn('maintenance_message');
});
}
}
マイグレーション実行
php artisan migrate
ロールバック
php artisan migrate:rollback
リセット
php artisan migrate:reset
初期データをSeedでセット
シーダー生成のためのartisanコマンドを叩く
php artisan make:seeder テーブル作成したクラス名TableSeeder
public function run()
{
//
DB::table('テーブル名')->insert([
'id' => 300,
'room_id' => 100,
'status' => 1,
'created' => date('Y-m-d H:i:s'),
'updated' => date('Y-m-d H:i:s'),
],
[
'room_id' => 101,
'status' => 0,
'created' => date('Y-m-d H:i:s'),
'updated' => date('Y-m-d H:i:s'),
],
}
シーダクラスをコールする為の設定
シーダクラスの定義が完了したら、このシーダクラスをシーディング実行時にコール(呼び出す)できるようにします。
seedsディレクトリにあるもう一つのファイルDatabaseSeeder.phpに以下を記述します。
laravel/database/seeds/DatabaseSeeder.php
public function run()
{
$this->call([
作成したテーブルのクラス名TableSeeder::class,
]);
}
シーディング実行
php artisan db:seed