1、簡介
遷移就像數據庫的版本控制,允許團隊簡單輕松的編輯并共享應用的數據庫表結構,遷移通常和Laravel的schema構建器結對從而可以很容易地構建應用的數據庫表結構。如果你曾經告知小組成員需要手動添加列到本地數據庫結構,那么這正是數據庫遷移所致力于解決的問題。
Laravel 的Schema門面提供了與數據庫系統無關的創建和操縱表的支持,在 Laravel 所支持的所有數據庫系統中提供一致的、優雅的、平滑的API。
2、生成遷移
使用 Artisan 命令make:migration來創建一個新的遷移:
1
|
php artisan make:migration create_users_table |
新的遷移位于database/migrations目錄下,每個遷移文件名都包含時間戳從而允許 Laravel 判斷其順序。
–table和–create選項可以用于指定表名以及該遷移是否要創建一個新的數據表。這些選項只需要簡單放在上述遷移命令后面并指定表名:
1
2
|
php artisan make:migration create_users_table –create=users php artisan make:migration add_votes_to_users_table –table=users |
如果你想要指定生成遷移的自定義輸出路徑,在執行make:migration命令時可以使用–path選項,提供的路徑應該是相對于應用根目錄的。
3、遷移結構
遷移類包含了兩個方法:up和down。up方法用于新增表,列或者索引到數據庫,而down方法就是up方法的反操作,和up里的操作相反。
在這兩個方法中你都要用到 Laravel 的schema構建器來創建和修改表,要了解更多Schema構建器提供的方法,參考其文檔。下面讓我們先看看創建flights表的簡單示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFlightsTable extends Migration{ /** * 運行遷移 * * @return void */ public function up() { Schema::create( 'flights' , function (Blueprint $table ) { $table ->increments( 'id' ); $table ->string( 'name' ); $table ->string( 'airline' ); $table ->timestamps(); }); } |
1
2
3
4
5
6
7
8
9
10
|
/** * 撤銷遷移 * * @return void */ public function down() { Schema::drop( 'flights' ); } } |
4、運行遷移
要運行應用中所有未執行的遷移,可以使用 Artisan 命令提供的migrate方法:
1
|
php artisan migrate |
注:如果你正在使用Homestead虛擬機,需要在虛擬機中運行上面這條命令。
在生產環境中強制運行遷移
有些遷移操作是毀滅性的,這意味著它們可能造成數據的丟失,為了避免在生產環境數據庫中運行這些命令,你將會在運行這些命令之前被提示并確認。想要強制運行這些命令而不被提示,可以使用–force:
1
|
php artisan migrate --force |
回滾遷移
想要回滾最新的一次遷移”操作“,可以使用rollback命令,注意這將會回滾最后一批運行的遷移,可能包含多個遷移文件:
1
|
php artisan migrate:rollback |
你也可以通過rollback命令上提供的step選項來回滾指定數目的遷移,例如,下面的命令將會回滾最后五條遷移:
1
|
php artisan migrate:rollback --step=5 |
migrate:reset命令將會回滾所有的應用遷移:
1
|
php artisan migrate:reset |
在單個命令中回滾/遷移
migrate:refresh命令將會先回滾所有數據庫遷移,然后運行migrate命令。這個命令可以有效的重建整個數據庫:
1
2
|
php artisan migrate:refresh php artisan migrate:refresh --seed |
當然,你也可以回滾或重建指定數量的遷移,通過refresh命令提供的step選項,例如,下面的命令將會回滾或重建最后五條遷移:
1
|
php artisan migrate:refresh --step=5 |
5、數據表
創建表
使用Schema門面上的create方法來創建新的數據表。create方法接收兩個參數,第一個是表名,第二個是獲取用于定義新表的Blueprint對象的閉包:
1
2
3
|
Schema::create( 'users' , function ( $table ) { $table ->increments( 'id' ); }); |
當然,創建新表的時候,可以使用schema構建器中的任意列方法來定義數據表的列。
檢查表/列是否存在
你可以輕松地使用 hasTable 和 hasColumn 方法檢查表或列是否存在:
1
2
3
4
5
6
7
|
if (Schema::hasTable( 'users' )) { // } if (Schema::hasColumn( 'users' , 'email' )) { // } |
連接&存儲引擎
如果你想要在一個數據庫連接上執行表結構操作,該數據庫連接并不是默認數據庫連接,使用connection方法:
1
2
3
|
Schema::connection( 'foo' )->create( 'users' , function ( $table ) { $table ->increments( 'id' ); }); |
要設置表的存儲引擎,在schema構建器上設置engine屬性:
1
2
3
4
|
Schema::create( 'users' , function ( $table ) { $table ->engine = 'InnoDB' ; $table ->increments( 'id' ); }); |
重命名/刪除表
要重命名一個已存在的數據表,使用rename方法:
1
|
Schema::rename( $from , $to ); |
要刪除一個已存在的數據表,可以使用drop或dropIfExists方法:
1
2
|
Schema::drop( 'users' ); Schema::dropIfExists( 'users' ); |
通過外鍵重命名表
在重命名表之前,需要驗證該表包含的外鍵在遷移文件中有明確的名字,而不是Laravel基于慣例分配的名字。否則,外鍵約束名將會指向舊的數據表。
6、列
創建列
要更新一個已存在的表,使用Schema門面上的table方法,和create方法一樣,table方法接收兩個參數:表名和獲取用于添加列到表的Blueprint實例的閉包:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->string( 'email' ); }); |
可用的列類型
當然,schema構建器包含一系列你可以用來構建表的列類型:
命令 描述
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
$table ->bigIncrements( 'id' ); 自增ID,類型為bigint $table ->bigInteger( 'votes' ); 等同于數據庫中的BIGINT類型 $table ->binary( 'data' ); 等同于數據庫中的BLOB類型 $table ->boolean( 'confirmed' ); 等同于數據庫中的BOOLEAN類型 $table ->char( 'name' , 4); 等同于數據庫中的CHAR類型 $table -> date ( 'created_at' ); 等同于數據庫中的 DATE 類型 $table ->dateTime( 'created_at' ); 等同于數據庫中的DATETIME類型 $table ->dateTimeTz( 'created_at' ); 等同于數據庫中的DATETIME類型(帶時區) $table ->decimal( 'amount' , 5, 2); 等同于數據庫中的DECIMAL類型,帶一個精度和范圍 $table ->double( 'column' , 15, 8); 等同于數據庫中的DOUBLE類型,帶精度, 總共15位數字,小數點后8位. $table ->enum( 'choices' , [ 'foo' , 'bar' ]); 等同于數據庫中的 ENUM類型 $table ->float( 'amount' ); 等同于數據庫中的 FLOAT 類型 $table ->increments( 'id' ); 數據庫主鍵自增ID $table ->integer( 'votes' ); 等同于數據庫中的 INTEGER 類型 $table ->ipAddress( 'visitor' ); 等同于數據庫中的 IP 地址 $table ->json( 'options' ); 等同于數據庫中的 JSON 類型 $table ->jsonb( 'options' ); 等同于數據庫中的 JSONB 類型 $table ->longText( 'description' ); 等同于數據庫中的 LONGTEXT 類型 $table ->macAddress( 'device' ); 等同于數據庫中的 MAC 地址 $table ->mediumIncrements( 'id' ); 自增ID,類型為無符號的mediumint $table ->mediumInteger( 'numbers' ); 等同于數據庫中的 MEDIUMINT類型 $table ->mediumText( 'description' ); 等同于數據庫中的 MEDIUMTEXT類型 $table ->morphs( 'taggable' ); 添加一個 INTEGER類型的 taggable_id 列和一個 STRING類型的 taggable_type列 $table ->nullableTimestamps(); 和 timestamps()一樣但允許 NULL值. $table ->rememberToken(); 添加一個 remember_token 列: VARCHAR(100) NULL. $table ->smallIncrements( 'id' ); 自增ID,類型為無符號的smallint $table ->smallInteger( 'votes' ); 等同于數據庫中的 SMALLINT 類型 $table ->softDeletes(); 新增一個 deleted_at 列 用于軟刪除. $table ->string( 'email' ); 等同于數據庫中的 VARCHAR 列 . $table ->string( 'name' , 100); 等同于數據庫中的 VARCHAR,帶一個長度 $table ->text( 'description' ); 等同于數據庫中的 TEXT 類型 $table ->time( 'sunrise' ); 等同于數據庫中的 TIME類型 $table ->timeTz( 'sunrise' ); 等同于數據庫中的 TIME 類型(帶時區) $table ->tinyInteger( 'numbers' ); 等同于數據庫中的 TINYINT 類型 $table ->timestamp( 'added_on' ); 等同于數據庫中的 TIMESTAMP 類型 $table ->timestampTz( 'added_on' ); 等同于數據庫中的 TIMESTAMP 類型(帶時區) $table ->timestamps(); 添加 created_at 和 updated_at列 $table ->timestampsTz(); 添加 created_at 和 updated_at列(帶時區) $table ->unsignedBigInteger( 'votes' ); 等同于數據庫中無符號的 BIGINT 類型 $table ->unsignedInteger( 'votes' ); 等同于數據庫中無符號的 INT 類型 $table ->unsignedMediumInteger( 'votes' ); 等同于數據庫中無符號的 MEDIUMINT 類型 $table ->unsignedSmallInteger( 'votes' ); 等同于數據庫中無符號的 SMALLINT 類型 $table ->unsignedTinyInteger( 'votes' ); 等同于數據庫中無符號的 TINYINT 類型 $table ->uuid( 'id' ); 等同于數據庫的UUID |
列修改器
除了上面列出的列類型之外,在添加列的時候還可以使用一些其它列“修改器”,例如,要使列默認為null,可以使用nullable方法:
1
2
|
Schema::table(‘users ', function (table) {table) {table->string(‘email' )->nullable(); }); |
下面是所有可用的列修改器列表,該列表不包含索引修改器:
修改器 描述
1
2
3
4
5
6
7
8
|
->after( 'column' ) 將該列置于另一個列之后 (僅適用于MySQL) ->comment( 'my comment' ) 添加注釋信息 -> default ( $value ) 指定列的默認值 ->first() 將該列置為表中第一個列 (僅適用于MySQL) ->nullable() 允許該列的值為NULL ->storedAs( $expression ) 創建一個存儲生成列(只支持MySQL) ->unsigned() 設置 integer 列為 UNSIGNED ->virtualAs( $expression ) 創建一個虛擬生成列(只支持MySQL) |
修改列
先決條件
在修改列之前,確保已經將doctrine/dbal依賴添加到composer.json文件,Doctrine DBAL 庫用于判斷列的當前狀態并創建對列進行指定調整所需的SQL語句:
1
|
composer require doctrine/dbal |
更新列屬性
change方法允許你修改已存在的列為新的類型,或者修改列的屬性。例如,你可能想要增加 string 類型列的尺寸,讓我們將name列的尺寸從 25 增加到 50:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->string( 'name' , 50)->change(); }); |
我們還可以修改該列允許 NULL 值:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->string( 'name' , 50)->nullable()->change(); }); |
重命名列
要重命名一個列,可以使用表結構構建器上的renameColumn方法,在重命名一個列之前,確保doctrine/dbal依賴已經添加到composer.json文件:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->renameColumn( 'from' , 'to' ); }); |
注:暫不支持enum類型的列的修改和重命名。
刪除列
要刪除一個列,使用schema構建器上的dropColumn方法:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->dropColumn( 'votes' ); }); |
你可以傳遞列名數組到dropColumn方法從表中刪除多個列:
1
2
3
|
Schema::table( 'users' , function ( $table ) { $table ->dropColumn([ 'votes' , 'avatar' , 'location' ]); }); |
注:在從SQLite數據庫刪除列之前,需要添加doctrine/dbal依賴到composer.json文件并在終端中運行composer update命令來安裝該庫。此外,SQLite數據庫暫不支持在單個遷移中刪除或修改多個列。
7、索引
創建索引
schema構建器支持多種類型的索引,首先,讓我們看一個指定列值為唯一索引的例子。要創建索引,可以使用unique方法:
1
|
$table ->string( 'email' )->unique(); |
此外,你可以在定義列之后創建索引,例如:
1
|
$table ->unique( 'email' ); |
你甚至可以傳遞列名數組到索引方法來創建組合索引:
1
|
$table ->index([ 'account_id' , 'created_at' ]); |
Laravel 會自動生成合理的索引名稱,但是你可以傳遞第二個參數到該方法用于指定索引名稱:
1
|
$table ->index( 'email' , 'my_index_name' ); |
可用索引類型
命令 描述
1
2
3
4
5
|
$table ->primary( 'id' ); 添加主鍵索引 $table ->primary([ 'first' , 'last' ]); 添加混合索引 $table ->unique( 'email' ); 添加唯一索引 $table ->unique( 'state' , 'my_index_name' ); 指定自定義索引名稱 $table ->index( 'state' ); 添加普通索引 |
刪除索引
要刪除索引,必須指定索引名。默認情況下,Laravel 自動分配適當的名稱給索引——簡單連接表名、列名和索引類型。下面是一些例子:
命令 描述
1
2
|
table−>dropPrimary(‘usersidprimary′);從“users”表中刪除主鍵索引table−>dropPrimary(‘usersidprimary′);從“users”表中刪除主鍵索引table->dropUnique(‘users_email_unique'); 從 “users”表中刪除唯一索引 $table ->dropIndex(‘geo_state_index'); 從 “geo”表中刪除普通索引 |
如果要傳遞列數組到刪除索引方法,那么相應的索引名稱將會通過數據表名、列和關鍵類型來自動生成:
1
2
|
Schema::table(‘geo ', function (table) {table) {table->dropIndex([‘state' ]); // Drops index ‘geo_state_index' }); |
外鍵約束
Laravel 還提供了創建外鍵約束的支持,用于在數據庫層面強制引用完整性。例如,我們在posts表中定義了一個引用users表的id列的user_id列:
1
2
3
|
Schema::table(‘posts ', function (table) {table) {table->integer(‘user_id' )->unsigned(); $table ->foreign(‘user_id ')->references(‘id' )->on(‘users'); }); |
你還可以為約束的“on delete”和“on update”屬性指定期望的動作:
1
2
3
|
$table ->foreign(‘user_id') ->references(‘id ')->on(‘users' ) ->onDelete(‘cascade'); |
要刪除一個外鍵,可以使用dropForeign方法。外鍵約束和索引使用同樣的命名規則——連接表名、外鍵名然后加上“_foreign”后綴:
1
|
$table ->dropForeign(‘posts_user_id_foreign'); |
或者,你還可以傳遞在刪除時會自動使用基于慣例的約束名數值數組:
1
|
$table ->dropForeign([‘user_id']); |
你可以在遷移時通過以下方法啟用或關閉外鍵約束:
1
2
|
Schema::enableForeignKeyConstraints(); Schema::disableForeignKeyConstraints(); |
以上這篇Laravel創建數據庫表結構的例子就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zhezhebie/article/details/78589093