環境
php 7.4.1
Mysql Ver 15.1 Distrib 10.4.11-MariaDB
Laravel 7.23.0
composer 1.10.9
それでは前回カラム名を変更しましたが今回はカラムを追加していきたいと思います!
それではいってみましょう(^O^)
Menu
マイグレーションファイルを作成(make:migration)
add_col_nameというphpファイルを作成していきたいと思います。
make:migrationコマンド(cmd/ターミナル)
1 | php artisan make:migration add_col_name_table --table=users |
database\migrations
コマンド実行で自動で2020_08_08_012045_add_col_name_table.phpファイルが作成されました。
upとdownの編集
今作成した020_08_08_012045_add_col_name_table.phpの中身も前回同様に自動で作成されてるのでカラム名の時と同じようにに変更するのはfunctionのupとdownの2か所のみです。
①public function up()
②public function down()
【今回追加するカラム】
姓名の名(firstname)と電話番号(tel)を指定箇所にカラムを追加したいと思います。
①upの処理(カラムを挿入)
$table->string(‘firstname’)->after(‘lastname’);
姓の後ろに名を追加
$table->string(‘tel’)->after(‘firstname’);
名の後ろに電話番号を追加
②downの処理(rollback巻き戻し)
$table->dropColumn(‘firstname’);
upでfirstnameを追加したならば、巻き戻し時はdropで削除
$table->dropColumn(‘tel’);
upでtelを追加したならば、巻き戻し時はdropで削除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public function up() //①の処理 { Schema::table('users', function (Blueprint $table) { $table->string('firstname')->after('lastname'); $table->string('tel')->after('firstname'); }); } /** * Reverse the migrations. * * @return void */ public function down() //②の処理 { Schema::table('users', function (Blueprint $table) { $table->dropColumn('firstname'); $table->dropColumn('tel'); }); } |
編集が終わったら次は早速データベースに追加していきたいと思います。
データベースに追加(migrate)
migrateさせて作成したファイルを読み込せてDBに追加します。
migrateコマンド(cmd/ターミナル)
1 | php artisan migrate |
もしエラーが出たら
インストール↓↓Doctrine DBALライブラリー
コマンド
1 | composer require doctrine/dbal |
データベースの確認
データベースにきちんとfirstnameとtelが追加されたかを確認します。
コマンド(cmd/ターミナル)
1 | desc users; |
【変更前】
【変更後】
firstnameとtelがきちんと追加され順番もOKです(*^^)v
まとめ
実行したことはたったの3つです。
①php artisan make:migration カラムを追加するためのファイル作成
②$table->カラムを追加すための処理
③php artisan migrate マイグレーションファイル実行(データベースにカラム追加)
【次回】データベースのカラムの属性値を変更(マイグレーション)
以上です。