Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.php
The Laravel Schema
facade provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel's supported database systems.laravel
遷移是一種數據庫版本控制,可讓團隊在修改數據庫結構的同時,保持彼此的進度一致。 遷移一般會和結構生成器一塊兒使用, 能夠簡單的管理數據庫結構。git
Laravel Schema 門面提供了 建立和操做數據的支持。 它對全部Laravel支持的數據庫系統分享了一樣的表達法,和豐富的API 。數據庫
To create a migration, use the make:migration
Artisan command:express
使用Artisan CLI的命令 make:migration 創建遷移文件json
php artisan make:migration create_users_table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
The new migration will be placed in your database/migrations
directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.數組
新的遷移文件放在database/migrations目錄下, 文件名包含時間戳記,在執行遷移時用來決定順序。 閉包
The --table
and --create
options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table:app
-- table 和 --create 參數 用來指定數據表名,和遷移是否要建立一個新數據表。這些選項針對特定的表簡單的填寫生成的基礎文件composer
php artisan make:migration add_votes_to_users_table --table=users
php artisan make:migration create_users_table --create=users
A migration class contains two methods: up
and down
. The up
method is used to add new tables, columns, or indexes to your database, while the down
method should simply reverse the operations performed by the up
method.
Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema
builder, check out its documentation. For example, let's look at a sample migration that creates a flights
table:
一個遷移類包含兩個方法: up 和 down. up方法用來對數據庫添加新的表,字段 或是 索引, 而down方法則是簡單的對up方法的反操做。
這兩個方法你可使用Laravel的Schema 構建器快速的建立和修改表。 要深刻了解Schema構建器的全部方法,請參考文檔, 如今來看一個簡單的例子,建立一個flights表。
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFlightsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('flights');
}
}
To run all outstanding migrations for your application, use the migrate
Artisan command. If you are using theHomestead virtual machine, you should run this command from within your VM:
要運行全部未完成的遷移,使用migration這個Artisan命令, 若是你使用 Homestead 虛擬機, 你應該在虛擬機裏面運行命令。
php artisan migrate
If you receive a "class not found" error when running migrations, try running the composer dump-autoload
command and re-issuing the migrate command.
若是運行遷移時你收到「class not found」的錯誤,嘗試運行composer dump-autoload命令,而後在從新運行migration 命令。
Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the --force
flag:
有一些遷移操做是破壞性的,意味着你要丟失數據,要防止你在生產數據庫運行這些命令,你會在命令執行前被提示確認,要忽略提示強制執行這些命令,使用—force選項。
php artisan migrate --force
To rollback the latest migration "operation", you may use the rollback
command. Note that this rolls back the last "batch" of migrations that ran, which may include multiple migration files:
要回滾上一次遷移,你可使用rollback命令,注意這會回滾上次的運行的批量遷移,你能夠包括多個遷移文件。
php artisan migrate:rollback
The migrate:reset
command will roll back all of your application's migrations:
而 migrate:reset 命令會回滾你全部應用的遷移
php artisan migrate:reset
The migrate:refresh
command will first roll back all of your database migrations, and then run the migrate
command. This command effectively re-creates your entire database:
migrate:refresh命令首先回滾全部的數據據遷移, 而後運行migrate 命令, 這個命令有效地重建了整個數據庫。
php artisan migrate:refresh
php artisan migrate:refresh --seed
To create a new database table, use the create
method on the Schema
facade. The create
method accepts two arguments. The first is the name of the table, while the second is a Closure
which receives a Blueprint
object used to define the new table:
建立新的數據庫表,使用Schema 門面的 create方法,這個create方法接受兩個引數。 第一個是表名, 第二個是一個閉包函數,接收一個Blueprint對象來定義表。
Schema::create('users', function ($table) {
$table->increments('id');
});
Of course, when creating the table, you may use any of the schema builder's column methods to define the table's columns.
固然,當建立表的時候,你可以使用Schema構造器中的 column 方法去定義這個表的字段。
You may easily check for the existence of a table or column using the hasTable
and hasColumn
methods:
你能夠很容易查看錶和字段是否存在,分別使用 hasTable 和 hasColumn 方法
if (Schema::hasTable('users')) {
//
}
if (Schema::hasColumn('users', 'email')) {
//
}
If you want to perform a schema operation on a database connection that is not your default connection, use theconnection
method:
若是你想在一個不是默認數據庫鏈接上執行一個數據庫結構(Schema)操做,使用connection方法。
Schema::connection('foo')->create('users', function ($table) {
$table->increments('id');
});
To set the storage engine for a table, set the engine
property on the schema builder:
設置一個表的存儲引擎,經過在schema構建器設置engine屬性來達到。
Schema::create('users', function ($table) {
$table->engine = 'InnoDB';
$table->increments('id');
});
To rename an existing database table, use the rename
method:
使用rename方法來重命名一個已經存在的數據表。
Schema::rename($from, $to);
To drop an existing table, you may use the drop
or dropIfExists
methods:
使用drop 或dropIfExists方法來刪除一個已經存在的表。
Schema::drop('users');
Schema::dropIfExists('users');
To update an existing table, we will use the table
method on the Schema
facade. Like the create
method, the table
method accepts two arguments: the name of the table and a Closure
that receives a Blueprint
instance we can use to add columns to the table:
要更新已經存在的表,咱們在Schema門面使用table方法,就像create方法,table方法接受兩個引數, 表名稱, 和閉包函數接受一個Blueprint對象, 可使用它來添加字段。
Schema::table('users', function ($table) {
$table->string('email');
});
Of course, the schema builder contains a variety of column types that you may use when building your tables:
固然,Schema構建器包含一系列字段類型,你能夠用來創建表結構。
命令 | 描述 |
$table –>bigIncrements(‘id’); | Incrementing ID using a 「big integer」 equivalent. |
$table->bigInteger(‘votes’); | BIGINT equivalent for the database. |
$table->binary(‘data’); | BLOB equivalent for the database. |
$table->boolean(‘confirmed’); | BOOLEAN equivalent for the database. |
$table->char(‘name’,4) | CHAR equivalent with a length |
$table->date(‘create_at’); | DATE equivalent for the database. |
$table->dateTime(‘create_at’); | DATETIME equivalent for the database. |
$table->decimal(‘amount’,5,2); | DECIMAL equivalent with a precision and scale. |
$table->double(‘column’,15,8); | DOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point. |
$table->enum(‘choices’,[‘foo’, ‘bar’]); | ENUM equivalent for the database. |
$table->float(‘amount’); | FLOAT equivalent for the database. |
$table->increments(‘id’); | Incrementing ID for the database(primary key). |
$table->integer(‘votes’); | INTEGER equivalent for the database. |
$table->json(‘options’); | JSON equivalent for the database. |
$table->jsonb(‘option’); | JSONB equivalent for the database. |
$table->longText(‘description’); | LONGTEXT equivalent for the database. |
$table->mediumInteger(‘numbers’); | MEDIUMINT equivalent for the database. |
$table->mediumText(‘description’); | MEDIUMTEXT equivalent for the database. |
$table->morphs(‘taggable’); | Adds INTEGER taggable_id and STRING taggable_type. |
$table->nullableTimestamps(); | Same as timestamps(), except allows NULLs. |
$table->rememberToken(); | Adds remember_token as VARCHAR(100) NULL |
$table->smallInteger(‘votes’); | SMALLINT equivalent for the database. |
$table->softDeletes(); | Adds deleted_at column for soft deletes. |
$table->string(‘email’); | VARCHAR equivalent column |
$table->string(‘name’, 100); | VARCHAR equivalent with a length |
$table->text(‘description’); | TEXT equivalent for the database. |
$table->time(‘sunrise’); | TIME equivalent for the database. |
$table->tinyInteger(‘numbers’); | TINYINT equivalent for the database. |
$table->timestamp(‘added_on’); | TIMESTAMP equivalent for the database. |
$table->timestamps(); | Adds created_at and updated_at columns. |
In addition to the column types listed above, there are several other column "modifiers" which you may use while adding the column. For example, to make the column "nullable", you may use the nullable
method:
在以上的字段類型以外,還有其餘幾個字段的「修改器」, 當你添加字段的時候可能會用,例如,要是要使一個字段變成」nullable「,你可使用nullable 方法:
Schema::table('users', function ($table) {
$table->string('email')->nullable();
});
Below is a list of all the available column modifiers. This list does not include the index modifiers:
如下是全部可用的字段修改器,不包括index修改器。
修改器 | 描述 |
->first() | Place the column 「first」 in the table(MySQL Only) |
->after(‘column’) | Place the column ‘after’ another column (MySQL Only) |
->nullable() | Allow NULL values to be inserted into the column |
->default($value) | Specify a 「default」value for the column |
->unsigned() | Set integer columns to UNSIGNED |
Before modifying a column, be sure to add the doctrine/dbal
dependency to your composer.json
file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column.
在修改字段以前,確認已經把 doctrine/dbal 依賴加入到你的composer.json文件,這個 Doctrine DBAL庫,是用來決定字段的如今狀態,和建立實現指定修改所需的SQL查詢。
The change
method allows you to modify an existing column to a new type, or modify the column's attributes. For example, you may wish to increase the size of a string column. To see the change
method in action, let's increase the size of the name
column from 25 to 50:
change 方法容許你改變一個已存在的字段到新的類型,或者修改字段的屬性,例如,你可能但願增長字符串字段的尺寸。要看看change方法的使用,咱們把name 字段的尺寸從25增長到50:
Schema::table('users', function ($table) {
$table->string('name', 50)->change();
});
咱們也能夠修改一個字段成爲 nullable :
Schema::table('users', function ($table) {
$table->string('name', 50)->nullable()->change();
});
To rename a column, you may use the renameColumn
method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal
dependency to your composer.json
file:
要重命名一個字段,在Schema構建器裏,你可使用 renameColumn 方法。 在重命名字段以前,要確認增長 doctrine/dbal依賴到composer.json文件裏。
Schema::table('users', function ($table) {
$table->renameColumn('from', 'to');
});
Note: 在表裏對
enum
字段 更名稱如今還不被支持.
To drop a column, use the dropColumn
method on the Schema builder:
要刪除字段,在Schema構建器裏使用dropColumn方法
Schema::table('users', function ($table) {
$table->dropColumn('votes');
});
You may drop multiple columns from a table by passing an array of column names to the dropColumn
method:
你可能要在一個表裏刪除多個字段,經過在dropColumn方法裏傳入字段名字的數組來達成。
Schema::table('users', function ($table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});
Note: Before dropping columns from a SQLite database, you will need to add the
doctrine/dbal
dependency to yourcomposer.json
file and run thecomposer update
command in your terminal to install the library.
The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can simply chain the unique
method onto the column definition:
schema構建器支持幾種類型的索引,首先讓咱們看一個例子,指定一個字段的值須惟一。 要建立這樣的索引,咱們只要簡單在column定義後連接unique方法。
$table->string('email')->unique();
Alternatively, you may create the index after defining the column. For example:
另外一種途徑,你能夠在定義字段以後,創建索引
$table->unique('email');
You may even pass an array of columns to an index method to create a compound index:
你更能夠傳入一個字段的數組到index方法來建立一個複雜索引
$table->index(['account_id', 'created_at']);
方法 | 描述 |
$table->primary(‘id’); | 增長一個主鍵 |
$table->primary(‘first’, ‘last’) | 增長一個複合鍵 |
$table->unique(‘email’); | 增長一個惟一索引 |
$table->index(‘state’); | 增長一個基本索引 |
To drop an index, you must specify the index's name. By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:
刪除一個索引,你必須指定索引的名字,默認,Laravel會自動指定一個合理的名字到給索引,只簡單地把表名,索引所在的字段名,和索引類型鏈接在一塊兒,這是例子。
方法 | 描述 |
$table->dropPrimary(‘users_id_primary’); | 從users表刪除主鍵 |
$table->dropUnique(‘users_email_unique’); | 從users表刪除惟一索引 |
$table->dropIndex(‘geo_state_index’); | 從geo表刪除基本索引 |
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id
column on the posts
table that references the id
column on ausers
table:
Laravel也提供了對外鍵束縛的支持,用來保證數據庫級別的參照完整性,例如,讓咱們在posts表定義要給user_id 字段,參照users表的id字段。
Schema::table('posts', function ($table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
You may also specify the desired action for the "on delete" and "on update" properties of the constraint:
你也能夠制定約束的」on delete」和」on update」屬性對應的動做
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
To drop a foreign key, you may use the dropForeign
method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":
要刪除一個外鍵,你可使用dropForeign方法,外鍵束縛使用和索引相同的命名規範, 咱們只要連接束縛中的表名和字段名而後結尾加上」_foreign」:
$table->dropForeign('posts_user_id_foreign');