環境
php 7.4.1
Mysql Ver 15.1 Distrib 10.4.11-MariaDB
Laravel 7.23.0
composer 1.10.9
前回はカラムを追加しました。
今回はカラムの属性値を変更します。
前回と手順はほぼ一緒なので前回のカラム追加ができたなら楽勝です\(^^)/
それではいってみましょう!
Menu
マイグレーションファイルを作成
add_col_Modifier_table。まずは属性値を変更するためのファイルを作成します。
とはいっても前回同様に下記の1文で自動でファイルと中身も作成してくれます。
make:migrationコマンド(cmd/ターミナル)
1 | php artisan make:migration add_col_Modifier_table --table=users |
database\migrations
コマンドを実行すると自動で2020_08_08_015846_add_col__modifier_table.phpが作成されます。
upとdownの編集(change)
作成したマイグレーションファイルの編集を行います。
カラム追加の時と同様に変更するのは下記のfunctionのupとdownの2か所のみです。
①public function up()
②public function down()
$table->変更
だけの簡単な処理です。
①upの処理(更新処理)
$table->string(‘tel’, 100)->change();
telのvarcharを255から100に変更します
②downの処理(rollback巻き戻し)
$table->string(‘tel’, 255)->change();
telのvarcharを100から255に元に戻します(upの逆にすればOK)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class AddColModifierTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('tel', 100)->change(); //①の処理 }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->string('tel', 255)->change(); //②の処理 }); } } |
編集が終わったら次はデータベースを更新していきます。
データベースのtelの属性値を更新
migrateさせて今作成したファイルを読み込ませデータベースを更新します。
migrateコマンド(cmd/ターミナル)
1 | php artisan migrate |
【エラー時】
インストール↓↓Doctrine DBALライブラリー
コマンド
1 | composer require doctrine/dbal |
データベースの確認
usersテーブルのtel属性値が変更されたかを確認します。
コマンド(cmd/ターミナル)
1 | desc users; |
【変更前】
【変更後】
telのvarcharが255から100にきちんと変更されています。
まとめ
今回実行したことはたったの3つです。
①php artisan make:migration カラムの属性値を変更するためのファイル作成
②$table->カラムの属性値を変更するための処理
③php artisan migrate マイグレーションファイル実行(データベース更新)
【次回】データベースにダミーデータを挿入する(seeder と faker)
以上です。