数据库迁移就像是数据库的版本控制,可让你的团队轻松修改并共享应用程序的数据库结构。迁移一般与 Laravel 的数据库结构生成器配合使用,让你轻松地构建数据库结构。若是你曾经试过让同事手动在数据库结构中添加字段,那么数据库迁移可让你再也不须要作这样的事情。php
Laravel Schema
facade 对全部 Laravel 支持的数据库系统提供了建立和操做数据表的相应支持。laravel
使用 Artisan 命令 make:migration
来建立迁移:数据库
php artisan make:migration create_users_table
新的迁移文件会被放置在 database/migrations
目录中。每一个迁移文件的名称都包含了一个时间戳,以便让 Laravel 确认迁移的顺序。express
--table
和 --create
选项可用来指定数据表的名称,或是该迁移被执行时是否将建立的新数据表。这些选项需在预生成迁移文件时填入指定的数据表:json
php artisan make:migration create_users_table --create=users php artisan make:migration add_votes_to_users_table --table=users
若是你想为生成的迁移指定一个自定义输出路径,则能够在运行 make:migration
命令时添加 --path
选项。给定的路径必须是相对于应用程序的基本路径。数组
迁移类一般会包含两个方法:up
和 down
。up
方法可为数据库添加新的数据表、字段或索引,而 down
方法则是 up
方法的逆操做。闭包
你能够在这两个方法中使用 Laravel 数据库结构生成器来建立以及修改数据表。若要了解 Schema
生成器中的全部可用方法,可查阅它的文档。如下的迁移实例会建立一张 flights
数据表:composer
<?php use Illuminate\Support\Facades\Schema; 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(); }); } /** * 回滚数据库迁移 * * @return void */ public function down() { Schema::drop('flights'); } }
使用 Artisan 命令 migrate
来运行全部未完成的迁移:ide
php artisan migrate
{note} 若是你使用的是 Homestead 虚拟机,则应该在虚拟机中执行命令。post
一些迁移操做是具备破坏性的,这意味着可能会致使数据丢失。为了防止有人在生产环境中运行这些命令,系统会在这些命令被运行以前与你进行确认。若是要强制忽略系统的提示运行命令,则可使用 --force
标记:
php artisan migrate --force
若要回滚最后一次迁移,可使用 rollback
命令。此命令将回滚最后一次「迁移」,其中可能包含多个迁移文件:
php artisan migrate:rollback
在 rollback
命令后加上 step
参数,你能够限制回滚迁移的个数。例如,如下命令将回滚最近五次迁移:
php artisan migrate:rollback --step=5
migrate:reset
命令能够回滚应用程序中的全部迁移:
php artisan migrate:reset
migrate:refresh
命令不只会回滚数据库的全部迁移还会接着运行 migrate
命令。这个命令能够高效地重建整个数据库:
php artisan migrate:refresh
// 刷新数据库结构并执行数据填充
php artisan migrate:refresh --seed
使用 refresh
命令并提供 step
参数来回滚并再执行最后指定的迁移数。例如,如下命令将回滚并从新执行最后五次迁移:
php artisan migrate:refresh --step=5
migrate:fresh
命令会从数据库中删除全部表,而后执行 migrate
命令:
php artisan migrate:fresh php artisan migrate:fresh --seed
可使用 Schema
facade 的 create
方法来建立新的数据库表。create
方法接受两个参数:第一个参数为数据表的名称,第二个参数是 闭包
,此闭包会接收一个用于定义新数据表的 Blueprint
对象:
Schema::create('users', function (Blueprint $table) { $table->increments('id'); });
固然,在建立数据表的时候,可使用任何数据库结构生成器的 字段方法 来定义数据表的字段。
可使用 hasTable
和 hasColumn
方法来检查数据表或字段是否存在:
if (Schema::hasTable('users')) { // } if (Schema::hasColumn('users', 'email')) { // }
若是要对非默认链接的数据库链接执行结构操做,可使用 connection
方法:
Schema::connection('foo')->create('users', function (Blueprint $table) { $table->increments('id'); });
你能够在数据库结构生成器上使用如下命令来定义表的选项:
命令 | 描述 |
---|---|
$table->engine = 'InnoDB'; |
指定表存储引擎 (MySQL) |
$table->charset = 'utf8'; |
指定数据表的默认字符集 (MySQL) |
$table->collation = 'utf8_unicode_ci'; |
指定数据表默认的排序规则 (MySQL) |
$table->temporary(); |
建立临时表(不支持SQL Server). |
若要重命名数据表,可使用 rename
方法:
Schema::rename($from, $to);
要删除数据表,可以使用 drop
或 dropIfExists
方法:
Schema::drop('users'); Schema::dropIfExists('users');
在重命名表以前,你应该验证表上的任何外键约束在迁移文件中都有明确的名称,而不是让 Laravel 按照约定来设置一个名称。不然,外键的约束名称将引用旧表名。
使用 Schema
facade 的 table
方法能够更新现有的数据表。如同 create
方法同样,table
方法会接受两个参数:一个是数据表的名称,另外一个则是接收能够用来向表中添加字段的 Blueprint
实例的闭包
:
Schema::table('users', function (Blueprint $table) { $table->string('email'); });
数据库结构生成器包含构建表时能够指定的各类字段类型:
命令 | 描述 |
---|---|
$table->bigIncrements('id'); |
递增 ID(主键),至关于「UNSIGNED BIG INTEGER」 |
$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', 8, 2); |
至关于带有精度与基数 DECIMAL |
$table->double('column', 8, 2); |
至关于带有精度与基数 DOUBLE |
$table->enum('level', ['easy', 'hard']); |
至关于 ENUM |
$table->float('amount', 8, 2); |
至关于带有精度与基数 FLOAT |
$table->geometry('positions'); |
至关于 GEOMETRY |
$table->geometryCollection('positions'); |
至关于 GEOMETRYCOLLECTION |
$table->increments('id'); |
递增的 ID (主键),至关于「UNSIGNED INTEGER」 |
$table->integer('votes'); |
至关于 INTEGER |
$table->ipAddress('visitor'); |
至关于 IP 地址 |
$table->json('options'); |
至关于 JSON |
$table->jsonb('options'); |
至关于 JSONB |
$table->lineString('positions'); |
至关于 LINESTRING |
$table->longText('description'); |
至关于 LONGTEXT |
$table->macAddress('device'); |
至关于 MAC 地址 |
$table->mediumIncrements('id'); |
递增 ID (主键) ,至关于「UNSIGNED MEDIUM INTEGER」 |
$table->mediumInteger('votes'); |
至关于 MEDIUMINT |
$table->mediumText('description'); |
至关于 MEDIUMTEXT |
$table->morphs('taggable'); |
至关于加入递增的 taggable_id 与字符串 taggable_type |
$table->multiLineString('positions'); |
至关于 MULTILINESTRING |
$table->multiPoint('positions'); |
至关于 MULTIPOINT |
$table->multiPolygon('positions'); |
至关于 MULTIPOLYGON |
$table->nullableMorphs('taggable'); |
至关于可空版本的 morphs() 字段 |
$table->nullableTimestamps(); |
至关于可空版本的 timestamps() 字段 |
$table->point('position'); |
至关于 POINT |
$table->polygon('positions'); |
至关于 POLYGON |
$table->rememberToken(); |
至关于可空版本的 VARCHAR(100) 的 remember_token 字段 |
$table->smallIncrements('id'); |
递增 ID (主键) ,至关于「UNSIGNED SMALL INTEGER」 |
$table->smallInteger('votes'); |
至关于 SMALLINT |
$table->softDeletes(); |
至关于为软删除添加一个可空的 deleted_at 字段 |
$table->softDeletesTz(); |
至关于为软删除添加一个可空的 带时区的 deleted_at 字段 |
$table->string('name', 100); |
至关于带长度的 VARCHAR |
$table->text('description'); |
至关于 TEXT |
$table->time('sunrise'); |
至关于 TIME |
$table->timeTz('sunrise'); |
至关于带时区的 TIME |
$table->timestamp('added_on'); |
至关于 TIMESTAMP |
$table->timestampTz('added_on'); |
至关于带时区的 TIMESTAMP |
$table->tinyIncrements('id'); |
至关于自动递增 UNSIGNED TINYINT |
$table->tinyInteger('votes'); |
至关于 TINYINT |
$table->unsignedBigInteger('votes'); |
至关于 Unsigned BIGINT |
$table->unsignedDecimal('amount', 8, 2); |
至关于带有精度和基数的 UNSIGNED DECIMAL |
$table->unsignedInteger('votes'); |
至关于 Unsigned INT |
$table->unsignedMediumInteger('votes'); |
至关于 Unsigned MEDIUMINT |
$table->unsignedSmallInteger('votes'); |
至关于 Unsigned SMALLINT |
$table->unsignedTinyInteger('votes'); |
至关于 Unsigned TINYINT |
$table->uuid('id'); |
至关于 UUID |
$table->year('birth_year'); |
至关于 YEAR |
除了上述列出的字段类型以外,还有几个能够在添加字段时使用的「修饰符」。例如,若是要把字段设置为「可空」,就使用 nullable
方法:
Schema::table('users', function (Blueprint $table) { $table->string('email')->nullable(); });
如下是全部可用的字段修饰符的列表。此列表不包括 索引修饰符:
修饰符 | 描述 |
---|---|
->after('column') |
将此字段放置在其它字段「以后」(仅限 MySQL) |
->autoIncrement() |
将 INTEGER 类型的字段设置为自动递增的主键 |
->charset('utf8') |
指定一个字符集(仅限 MySQL) |
->collation('utf8_unicode_ci') |
指定列的排序规则(仅限 MySQL/SQL Server) |
->comment('my comment') |
为字段增长注释(仅限 MySQL) |
->default($value) |
为字段指定「默认」值 |
->first() |
将此字段放置在数据表的「首位」(仅限 MySQL) |
->nullable($value = true) |
(默认状况下)此字段容许写入 NULL 值 |
->storedAs($expression) |
建立一个存储生成的字段 (仅限 MySQL) |
->unsigned() |
设置 integer 类型的字段为 UNSIGNED (仅限 MySQL) |
->useCurrent() |
将 TIMESTAMP 类型的字段设置为使用 CURRENT_TIMESTAMP 做为默认值 |
->virtualAs($expression) |
建立一个虚拟生成的字段 (仅限 MySQL) |
在修改字段以前,请确保将 doctrine/dbal
依赖添加到 composer.json
文件中。Doctrine DBAL 库用于肯定字段的当前状态,并建立对该字段进行指定调整所需的 SQL 查询:
composer require doctrine/dbal
change
方法能够将现有的字段类型修改成新的类型或修改属性。好比,你可能想增长字符串字段的长度,可使用 change
方法把 name
字段的长度从 25 增长到 50 :
Schema::table('users', function (Blueprint $table) { $table->string('name', 50)->change(); });
将字段修改成可空:
Schema::table('users', function (Blueprint $table) { $table->string('name', 50)->nullable()->change(); });
{note} 只有下面的字段类型不能被「修改」: bigInteger、binary、boolean、date、dateTime、dateTimeTz、 decimal、integer、json、longText、mediumText、smallInteger、string、text、time、unsignedBigInteger、unsignedInteger 和 unsignedSmallInteger。
可使用结构生成器上的 renameColumn
方法来重命名字段。在重命名字段前,请确保你的 composer.json
文件内已经加入 doctrine/dbal
依赖:
Schema::table('users', function (Blueprint $table) { $table->renameColumn('from', 'to'); });
{note} 当前不支持
enum
类型的字段重命名。
可使用结构生成器上的 dropColumn
方法来删除字段。在从 SQLite 数据库删除字段前,你须要在 composer.json
文件中加入 doctrine/dbal
依赖并在终端执行 composer update
来安装该依赖:
Schema::table('users', function (Blueprint $table) { $table->dropColumn('votes'); });
你能够传递一个字段数组给 dropCloumn
方法来删除多个字段:
Schema::table('users', function (Blueprint $table) { $table->dropColumn(['votes', 'avatar', 'location']); });
{note} 不支持在使用 SQLite 数据库时在单个迁移中删除或修改多个字段。
命令 | 描述 |
---|---|
$table->dropRememberToken(); |
删除 remember_token 字段 |
$table->dropSoftDeletes(); |
删除 deleted_at 字段 |
$table->dropSoftDeletesTz(); |
dropSoftDeletes() 方法的别名 |
$table->dropTimestamps(); |
删除 created_at 和 updated_at 字段 |
$table->dropTimestampsTz(); |
dropTimestamps() 方法的别名 |
结构生成器支持多种类型的索引。首先,先指定字段值惟一,即简单地在字段定义以后链式调用 unique
方法来建立索引,例如:
$table->string('email')->unique();
或者,你也能够在定义完字段以后建立索引。例如:
$table->unique('email');
你甚至能够将数组传递给索引方法来建立一个复合(或合成)索引:
$table->index(['account_id', 'created_at']);
Laravel 会自动生成一个合理的索引名称,但你也能够传递第二个参数来自定义索引名称:
$table->index('email', 'unique_email');
命令 | 描述 |
---|---|
$table->primary('id'); |
添加主键 |
$table->primary(['id', 'parent_id']); |
添加复合键 |
$table->unique('email'); |
添加惟一索引 |
$table->index('state'); |
添加普通索引 |
$table->spatialIndex('location'); |
添加空间索引( SQLite 除外) |
Laravel 默认使用 utf8mb4
字符,它支持在数据库中存储「emojis」。若是你是在版本低于5.7.7 的 MySQL release 或者版本低于10.2.2 的 MariaDB release 上建立索引,那就须要你手动配置迁移生成的默认字符串长度。即在 AppServiceProvider
中调用 Schema::defaultStringLength
方法来配置它:
use Illuminate\Support\Facades\Schema; /** * 引导任何应用程序服务 * * @return void */ public function boot() { Schema::defaultStringLength(191); }
或者,你能够开启数据库的 innodb_large_prefix
选项,至于如何正确开启,请自行查阅数据库文档。
若要移除索引,则必须指定索引的名称。Laravel 默认会自动给索引分配合理的名称。其将数据表名称、索引的字段名称及索引类型简单地链接在了一块儿。举例以下:
命令 | 描述 |
---|---|
$table->dropPrimary('users_id_primary'); |
从「users」表中删除主键。 |
$table->dropUnique('users_email_unique'); |
从「users」表中删除惟一索引。 |
$table->dropIndex('geo_state_index'); |
从「geo」表中删除基本索引。 |
$table->dropSpatialIndex('geo_location_spatialindex'); |
从「geo」表中删除空间索引(SQLite除外)。 |
若是将字段数组传递给 dropIndex
方法,会删除根据表名、字段和键类型生成的索引名称:
Schema::table('geo', function (Blueprint $table) { $table->dropIndex(['state']); // 移除索引 'geo_state_index' });
Laravel 还支持建立用于在数据库层中的强制引用完整性的外键约束。例如,让咱们在 posts
表上定义一个引用 users
表的 id
字段的 user_id
字段:
Schema::table('posts', function (Blueprint $table) { $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); });
还能够为约束的「on delete」和「on update」属性指定所需的操做:
$table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade');
你可使用 dropForeign
方法删除外键。外键约束采用的命名方式与索引相同。即,将数据表名称和约束的字段链接起来,接着加上「_foreign」后缀:
$table->dropForeign('posts_user_id_foreign');
或者,你也能够传递一个字段数组,在删除的时候会按照约定自动转换为对应的外键名称:
$table->dropForeign(['user_id']);
你能够在迁移文件里使用如下方法来开启或关闭外键约束:
Schema::enableForeignKeyConstraints(); Schema::disableForeignKeyConstraints();
本文转载而来!本文连接来源于 https://laravel-china.org/docs/laravel/5.5/migrations/1329#generating-migrations