2025年6月10日 星期二

Laravel 12 Migration 遷移-資料庫版本控制


Migration 是名詞,代表的是準備用來變更資料庫結構的檔案,但本身無法執行。 Migrate 是動詞,它是用來執行 Migration 的內容。

一、預設的Migration指令
指令:php artisan migrate

二、完成migrations的檔案位置:
database/migrations/
三、設定資料庫為mysql
1.修改.env設定

2.在命令提示字元,打上 
php artisan migrate

3.在網址打上:http://localhost:8080/phpmyadmin/index.php?route=/database/structure&db=students
就可以看到新增students資料庫,裡面資料表已建立完成。
四、如何建立自己的migration
1.指令:
php artisan make:migration StudentsTable

就會建立自己的migration,但是內部的程式碼只有兩個空函式,分別是up與down。

2.指令:
php artisan make:migration create_students_table

就會建立自己的migration,但是內部的程式碼只有兩個函式,分別是up與down,並建立基本的欄位。

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');
然後下指令:php artisan migrate
這時如果出現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

2.取消變更幾次的指令:
php artisan migrate:rollback --step=2


3.取消變更到初始位置的指令:
php artisan migrate:reset

接下來再來處理:
                            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


沒有留言:

張貼留言

Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面

相關系列文章: 1. 在 windows 10 安裝 laravel 12 studentManagement環境與設定 2. laravel 12 route 路由 3. laravel 12 Blade Templates 網頁模版 4. laravel 12 Control...