搜尋
首頁php框架ThinkPHPthinkPHP使用migrate遷移資料庫

thinkPHP使用migrate遷移資料庫

May 27, 2020 am 09:08 AM
thinkphp

thinkPHP使用migrate遷移資料庫

thinkPHP的資料庫遷移工具:topthink/think-migration

一:安裝topthink/think-migration

這裡注意你安裝topthink/ think-migration時需要注意你的thinkPHP版本,這裡我的thinkPHP版本是5.1,所以可以安裝topthink/think-migration的2.0版本,無法安裝3.0版本,選擇你適合的版本進行安裝

composer require topthink/think-migration=2.0.*

安裝完成之後在命令列執行:

php think

如下表示migrate安裝成功

thinkPHP使用migrate遷移資料庫

#二:使用topthink/think-migration實作資料庫遷移

1:建立遷移類別

在命令列執行

php think migrate:create CreateUser

執行完成之後我們就和在./database/migrateions目錄下建立一個migrate遷移檔案

thinkPHP使用migrate遷移資料庫

#2:實作資料庫遷移

[1]:migrate程式碼說明:

在migrate中有三個方法

up:在migrate: run時執行(前提是檔案中不存在change方法)

down:在migrate:rollback時執行(前提是檔案中不存在change方法)

change:migrate:run 和migrate :rollback時執行(如果存在該方法則不會去執行up 與down)

一般情況下我一般將migrate文件中的change方法刪除,up方法專門放置新增和更新表的操作, down方法放置刪除表和刪除欄位操作

(1)新增表格:

// create the table
$table = $this->table('user', ['id' => 'user_id', 'comment' => '用户表', 'engine' => 'MyISAM', '']);
$table->addColumn('user_name', 'string', ['limit' => 15, 'default' => '', 'comment' => '用户名'])
    ->addColumn('password', 'string', ['limit' => 15, 'default' => '', 'comment' => '密码',])
    ->addColumn('status', 'boolean', ['limit' => 1, 'default' => 0, 'comment' => '状态'])
    ->addIndex(['user_name'], ['unique' => true])//为user_name创建索引并设置唯一(唯一索引)
    ->addTimestamps()//默认生成create_time和update_time两个字段
    ->create();

(2)更新表:

$this->table('user')
    ->addColumn('test', 'string', ['limit' => 15, 'default' => '', 'comment' => '测试'])//在user表中增加一个test字段
    ->update();

(3)刪除表:

$this->table('user')->drop();

(4)刪除欄位

$this->table('user')
    ->removeColumn('test')//删除user表中的test字段
    ->save();

[2]:migrate指令:

migrate常用的指令有三個,分別為:

php think migrate:create CreateUser  #创建一个迁移类
php think migrate:run  #执行迁移
php think migrate:rollback #迁移回滚

推薦教學: 《TP5

以上是thinkPHP使用migrate遷移資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具