前言
大家都知道,現(xiàn)在的開發(fā)測試都是講究多人團(tuán)隊協(xié)作完成,每個人都有本地環(huán)境,在以前我們一般是手動的添加數(shù)據(jù),比如在數(shù)據(jù)庫查詢器中使用sql語句進(jìn)行數(shù)據(jù)插入。如果數(shù)據(jù)較少,那還是蠻輕松的,但是如果數(shù)據(jù)過大,那就很蛋疼了,但是這在Laravel中就很輕松,可以使用數(shù)據(jù)遷移。
本文就詳細(xì)的介紹了關(guān)于Laravel中migrate使用的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹:
生成遷移
命令:
Migration
php artisan make:migration create_users_table
意思:創(chuàng)建一個遷移,其實(shí)就是創(chuàng)建一張名為users的表。
接著你便能在database/migrations這個目錄下找到與2014_10_12_000000_create_users_table.php這個類似的文件。
和以前用php語句創(chuàng)建表一樣,我們可以在2014_10_12_000000_create_users_table.php這個文件中寫上我們要創(chuàng)建表的字段及約束條件。
–table和–create選項可以用于指定表名以及該遷移是否要創(chuàng)建一個新的數(shù)據(jù)表。這些選項只需要簡單放在上述遷移命令后面并指定表名,如果你想要指定生成遷移的自定義輸出路徑,在執(zhí)行make:migration
命令時可以使用–path選項,提供的路徑應(yīng)該是相對于應(yīng)用根目錄的。
遷移結(jié)構(gòu)
一個migration類包含兩個方法up和down。
up中主要包含創(chuàng)建表的具體內(nèi)容。
down中和前者相反。
Schema::create
接受兩個參數(shù)。第一個是你要創(chuàng)建表的表名;第二個是一個閉包(匿名函數(shù)),獲取用于定義新表的 Blueprint 對象。
Migration
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
運(yùn)行遷移
要運(yùn)行應(yīng)用中所有未執(zhí)行的遷移,可以使用 Artisan 命令的migrate方法。
Migration
php artisan migrate
回滾遷移
想要回滾最新的一次遷移”操作“,可以使用rollback命令,注意這將會回滾最后一批運(yùn)行的遷移,可能包含多個遷移文件:
Migration
php artisan migrate:rollback
migrate:reset命令將會回滾所有的應(yīng)用遷移:
Migration
php artisan migrate:reset
在單個命令中回滾/遷移
migrate:refresh
命令將會先回滾所有數(shù)據(jù)庫遷移,然后運(yùn)行migrate命令。這個命令可以有效的重建整個數(shù)據(jù)庫:
Migration
php artisan migrate:refresh php artisan migrate:refresh --seed
常用遷移屬性
$table->increments(‘id'); | 數(shù)據(jù)庫主鍵自增 ID |
$table->integer(‘votes'); | 等同于數(shù)據(jù)庫中的 INTEGER 類型 |
$table->float(‘a(chǎn)mount'); | 等同于數(shù)據(jù)庫中的 FLOAT 類型 |
$table->char(‘name', 4); | 等同于數(shù)據(jù)庫中的 CHAR 類型 |
$table->dateTime(‘created_at'); | 等同于數(shù)據(jù)庫中的 DATETIME 類型 |
$table->enum(‘choices', [‘foo','bar']); | 等同于數(shù)據(jù)庫中的 ENUM 類型 |
$table->tinyInteger(‘numbers'); | 等同于數(shù)據(jù)庫中的 TINYINT 類型 |
$table->timestamps(); | 添加 created_at 和 updated_at 列 |
一些列名約束條件的寫法
Migration
Schema::table('users', function ($table) { $table->integer('votes')->unsigned(); //無符號類型 });
常用約束