相關系列文章:
Migration 是名詞,代表的是準備用來變更資料庫結構的檔案,但本身無法執行。 Migrate 是動詞,它是用來執行 Migration 的內容。
一、預設的Migration指令
指令:php artisan migrate
二、完成migrations的檔案位置:
database/migrations/
1.修改.env設定
php artisan migrate
就可以看到新增students資料庫,裡面資料表已建立完成。
四、如何建立自己的migration1.指令:
php artisan make:migration StudentsTable
2.指令:
php artisan make:migration create_students_table
3.在函式up裡面,出現兩個欄位 id() 與 timestamps()
$table->id();
$table->timestamps();
其中 id() 是主鍵,timestamps()是時間戳記。
此時,下指令:php artisan migrate
就會得到三個欄位,分別是id、created_at、updated_at
如果想了解更多,請到https://laravel.com/docs/12.x/migrations#creating-columns。接下來新增三個欄位
$table->string('name');
$table->string('email');
$table->integer('age');
這時如果出現Nothing to migrate
則可以先用
php artisan migrate:rollback
再用
php artisan migrate
就可以得到相對應的資料表欄位
五、若要在"使用中的資料表"中新增欄位,要怎麼做呢?
1.在命令提示列中,
php artisan make:migrations addDateOfBirthToStudents --table=students
2.在新增的2025_06_27_070357_add_date_of_birth_to_students.php進行編輯
$table->dateTime('date_of_birth')->nullable();
$table->enum('gender', ['f','m'])->default('m');
與
$table->dropColumn('date_of_birth');
$table->dropColumn('gender');
如下圖:
接下來使用
php artisan migrate
3.在命令提示列中,
php artisan make:migration addUserIdToStudents --table=students
此時會新增2025_06_29_050439_add_user_id_to_students.php
裡面會有兩個func,分別是up()與down()
up()要加入限制
$table->foreignId('user_id')->constrained('users')->onDelete('cascade')->onUpdate('cascade');
down()要加入
$table->dropforeign(['user_id']);
$table->dropColumn(['user_id']);
六、取消變更的指令
1.取消變更的指令:
php artisan migrate:rollback
php artisan migrate
就會建立起所有的表格。
4.清除所有變更再建立起所有的表格的指令:
php artisan migrate:fresh
該指令的效果php artisan migrate:reset + php artisan migrate
1.Laravel 12 – Introduction to Migrations: Manage Your Database Efficiently
沒有留言:
張貼留言