iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
1
Software Development

在後花園遇見LP,Laravel及PHP的甜蜜糾纏,火熱上映系列 第 17

✾後花園D17✾-我們要搬去哪裡呢?(Migration入門介紹)

ㄎ本系列文的環境狀態,可點擊此連結後花園環境參考

migration 我們是要搬去哪裡呢?那裡會有什麼呢?

產生新的migration檔案

⭐︎ 注意 ⭐︎ 要執行下列指令前,請務必要先建好相對應的資料庫,在下用自身在 mysql 建立的 BackGrden 資料庫對應 .env 檔做了張圖給看倌們參考,避免大家想說爲何下了指令卻沒有反應。

(謎之音:那是你沒建資料庫或還沒締結資料庫連結啊~~~)

輸入指令創建出 migration

$ php artisan make:migration create_flowers_table

新建立的檔案會產生在路徑 database/migrations 的資料夾下,見下圖

每個 migration class 都會有兩個 function 分別是 updown

function up:用於新增資料表、欄位、索引到資料庫中。

function down:用於反向執行回溯up的動作。

建立資料表

路徑:database/migrations/...日期create_flowers_table

如果要建立資料表,需將程式寫入 function up中

<?php
    public function up()
    {
        Schema::create('flowers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->timestamps();
        });
    }
    
    
    public function down()
    {
        Schema::dropIfExists('flowers');     // 刪除資料表,可用drop或dropIfExists
    }
    

欄位類型或欄位修飾,若想知道更多,可去參考官方文件-Database: Migrations

執行 migrations

migrate ,會執行 up() 方法來建立資料表

$ php artisan migrate

migrate:rollback ,會執行 down() 移除這個資料表。

$ php artisan migrate:rollback

migrate:reset ,還原應用程式的所有遷移。

$ php artisan migrate:reset

migrate:refresh ,還原資料庫的所有遷移

$ php artisan migrate:refresh

今天 Migrations 的介紹就先這樣囉!

想知道更多,可參考下列連結:
❁ Day7-[Laravel 的安裝與架設] Migration schema part1
❁ 初心者之路#10 – Migrations 和 Schema
❁ Laravel 學習筆記(8) - Migration 和 Model
❁ Day08 【Laravel 學習歷程】- 基本設置
❁ Laravel道場-資料庫:遷移Migration


上一篇
✾後花園D16✾-資料庫跟我締結契約吧!(Laravel資料庫及env設定)
下一篇
✾後花園D18✾-命名陷阱: Migration 及 Eloquent Model
系列文
在後花園遇見LP,Laravel及PHP的甜蜜糾纏,火熱上映49
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言