相關系列文章:
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
一、預設的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:migration 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






















沒有留言:
張貼留言