Featured image of post Day 11. 建立資料表: Migration

Day 11. 建立資料表: Migration

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

專案連結: github - laravel7 之 30 天分享

上一篇: Day 10. Authentication-3 忘記密碼/重設密碼
結束會員註冊登入流程
準備要來跟大家聊聊 Model
聊 Model 之前,先分享一下用來建立資料表的工具 - Migration,

主要

一樣,上文件

我們平常 寫 code 版控有 git 可以追蹤 code 的版本及異動,
migration 簡單說就是資料表的 git、資料表的版本控制
Laravel 會透過這些 migration 的檔案們,執行對資料表的異動

建立 migration

Model、migration 一起建立

平常我都是建立 model 順便建立 mgiration
假設我今天要建立一個 UserProfile, 只要在 make:model-m 就會一起產生 migration 相對省事
指令

1
php artisan make:model Models/UserProfile -m

也可以單獨 建立 migration、Model

  1. migration 命名規則是這樣的 create_<table_name>_table
    /database/migrations/ 就會產生對應的檔案
1
php artisan make:migration create_user_profiles_table
  1. Model
1
php artisan make:model Model/UserProfile 

編輯 migration

這裡我們先略過 Model 不談,執行完上面後就可以編輯你們的 Migration 了

檔案 database/migrations/2022_11_14_122200_create_user_profiles_table.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class CreateUserProfilesTable extends Migration
{
    public function up()
    {
        Schema::create('user_profiles', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }


    public function down()
    {
        Schema::dropIfExists('user_profiles');
    }
}

這邊你會看到兩個 function,up()down()

up()

主要放你要執行的資料表結構宣告 ex: varchar、int、date。之類的

down()

每次執行一次 migrater就會有一個 batch(版本)
down 就是 rollbak migrate 要使用的被回滾的資料表
這邊都是 create table 所以都是 drop 那個 table

資料表欄位如何宣告?

附上 文件
裏面有附上所有資料庫的型別,看你需要哪些欄位

外來鍵

外來鍵如果要關聯比較特別
我都直接這樣宣告
可以參考 文件

1
2
3
4
5
6
7
8
9
$table->foreignId('user_id')
    ->constrained('users')
    ->onUpdate('cascade')
    ->onDelete('cascade');
// $table
// ->foreignId('<你的欄位名稱>')
// ->constrained('<你要關聯的表>')
// ->onUpdate('cascade')
// ->onDelete('cascade');

Table註解

基本上我每個上去的欄位都會註解,table 也不例外
不過 Laravel Migration 沒有表的註解
所以我都透過 DB class 直接對表註解
指令如下

1
2
3
4
5
// use
use Illuminate\Support\Facades\DB;

// Table註解
DB::statement("ALTER TABLE `user_profiles` comment '使用者基本資料'");

執行 migration

只需要執行這個指令就會依照剛剛建立的產生資料表

1
php artisan migrate

後悔了要回滾 table

1
php artisan migrate:rollback

每次回滾 migration 就是回滾最新的 batch 一次
如果要多版號可以

1
2
# 回滾 3 個 batch
php artisan migrate:rollback --batch=3

如果要全部重來可以

1
php artisan migrate:reset

基本上除非開發階段,很少會 rollback/reset

捲土重來

開發階段很好用的指令,全部回滾再全部重建 refresh

1
php artisan migrate:refresh

這樣就會全部依照原本的樣子全部重跑,
當然此時的 batch 會全部變成 1 哦,因為重來了

狀態

可以透過這個指令查看目前執行狀況

1
php artisan migrate:status
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy