【Laravel】マイグレーション
Laravel公式ドキュメント-マイグレーションの私的アウトプット
準備
マイグレーションを試すためDBも用意した
項目 | 名前 |
---|---|
DBユーザ名 | testuser |
DB | test |
マイグレーション
マイグレーションとはDBのバージョンコントロール
マイグレ−ション作成
php artisan make:migration create_テーブル名_table
テーブル名は複数形にする
2つの--create
と--table
オプションがある。
公式によればこう説明されている
--table
と--create
オプションも、テーブル名とマイグレーションで新しいテーブルを生成するかを指定するために使用できます。これらのオプションは生成するマイグレーションスタブの中へ指定したテーブルをあらかじめ埋め込みます。
参考
Laravel 7.x データベース:マイグレーション
何言ってるかわかんないから以下コマンドを実行
php artisan make:migration create_users1_table
php artisan make:migration create_users2_table --table=users
php artisan make:migration create_users3_table --create=users
php artisan make:migration add_votes_to_users_table --table=users
そうしてわかったことはupメソッドの中でSchemaクラスの静的メソッドが変わる
オプション | 説明 |
---|---|
--create | オプションなしと変わらない |
--table | すでに存在するテーブルを更新する |
マイグレーション構造
メソッド | 説明 |
---|---|
up | 新しいテーブル、カラム、インデックスを追加 |
down | upメソッドの処理をもとに戻す |
マイグレーション実行
php artisan migrate[オプション1] [オプション2]
オプション
オプション | 説明 |
---|---|
:rollback | 最後のマイグレーション操作にロールバック |
:refresh | 最初似ロールバックしてmigrate コマンドを実行。つまりデータベース全体を作り直すのに適してる
|
:fresh | 全テーブル削除後にmigrate コマンドを実行 |
オプション2
オプション | 説明 |
---|---|
--seed | シード実行 |
テーブル
テーブル作成
Schema::create('users', function (Blueprint $table) {
$table->id();
});
テーブル名変更
Schema::create
を使う
Schema::rename($from, $to);
テーブル削除
Schema::drop('users');
Schema::dropIfExists('users');
drop
かdropIfExists
メソッドを使う
dropIfExists
を使っていったほうが良さげかな
カラム
カラム作成
Schema::table
を使う
Schema::table('users', function (Blueprint $table) {
$table->string('email');
});
テーブル作成のマイグレーションでオプションなしで作成されたファイルに書かれている$table->id();
の意味が載っていた↓
カラムタイプ | 意味 |
---|---|
$table->id(); |
$table->bigIncrements('id') のエイリアス |
カラム修飾子
NULLを許さない定義にするときとかはnullable
メソッドを使う
Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
});
カラム変更
まずは準備
composer require doctrine/dbal
カラム属性の変更
change
メソッドを使う
//文字長を25から50に変更
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->change();
});
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->nullable()->change();
});
カラム名変更
renameColumn
メソッドを使う
ここで先のcomposerで追加したものを使う
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
カラム削除
dropColumn
メソッドを使う
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
この引数に配列を渡すと複数カラムを削除できる
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});
Author And Source
この問題について(【Laravel】マイグレーション), 我々は、より多くの情報をここで見つけました https://qiita.com/oouaioi/items/fe2924145482a3e50251著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .