简介
数据库迁移类似于版本控制系统,使团队能够便捷地编辑和共享应用的数据库表结构。通常它与 Laravel 的 Schema 构建器配合使用,简化应用数据库表的构建过程。若曾遇到需手动通知团队成员在本地数据库中手动添加列以维持开发环境的情况,迁移正是解决此类问题的方案。
Laravel 的 Schema 门面为所有支持的数据库系统提供了一致、优雅且流式的 API,支持跨数据库系统的表创建与操作。
生成迁移
可通过 Artisan 命令 make:migration 来创建新的迁移文件:
php artisan make:migration create_users_table
新生成的迁移文件存放于 database/migrations 目录下,文件名包含时间戳,Laravel 据此判断执行顺序。
可使用 --table 和 --create 选项指定表名及该迁移是创建新表还是修改现有表。只需在迁移命令后附加这些选项并指定表名即可:
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 构建器来创建和修改表。更多关于 Schema 构建器的方法请参阅其文档。以下是一个创建 flights 表的简单示例:
<?php
use Illuminate\Support\Facades\Schema;
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');
}
}
运行迁移
要执行应用中所有未运行的迁移,可使用 Artisan 提供的 migrate 命令:
php artisan migrate
注意:若使用 Homestead 虚拟机,需在虚拟机内部运行上述命令。
在生产环境中强制运行迁移
部分迁移操作具有破坏性,可能导致数据丢失。为防止在生产环境中意外运行这些命令,系统会在执行前提示确认。若要跳过提示强制运行,可使用 --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 门面上的 create 方法可创建新数据表。该方法接收两个参数:表名和一个获取 Blueprint 对象(用于定义新表)的闭包:
Schema::create('users', function ($table) {
$table->increments('id');
});
当然,在创建新表时,可使用 Schema 构建器中的任意列方法来定义数据表的列。
检查表/列是否存在
可使用 hasTable 和 hasColumn 方法轻松检查表或列是否存在:
if (Schema::hasTable('users')) {
//
}
if (Schema::hasColumn('users', 'email')) {
//
}
数据库连接 & 表选项
若要在非默认数据库连接上执行表结构操作,可使用 connection 方法:
Schema::connection('foo')->create('users', function (Blueprint $table) {
$table->increments('id');
});
要设置表的存储引擎、字符编码等选项,可在 Schema 构建器上使用如下命令:
| 命令 | 描述 |
|---|---|
| $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 门面上的 table 方法。与 create 方法类似,table 方法接收两个参数:表名和获取用于添加列到表的 Blueprint 实例的闭包:
Schema::table('users', function (Blueprint $table) {
$table->string('email');
});
可用的数据列类型
Schema 构建器包含一系列可用于构建表的列类型:
| 命令 | 描述 |
|---|---|
| $table->bigIncrements('id'); | 等同于自增 UNSIGNED 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('level', ['easy', 'hard']); | 等同于 ENUM 类型列 |
| $table->float('amount', 8, 2); | 等同于 FLOAT 类型列,带精度和总位数 |
| $table->geometry('positions'); | 等同于 GEOMETRY 类型列 |
| $table->geometryCollection('positions'); | 等同于 GEOMETRYCOLLECTION 类型列 |
| $table->increments('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'); | 等同于自增 UNSIGNED MEDIUMINT 类型列(主键) |
| $table->mediumInteger('numbers'); | 等同于 MEDIUMINT 类型列 |
| $table->mediumText('description'); | 等同于 MEDIUMTEXT 类型列 |
| $table->morphs('taggable'); | 添加一个 UNSIGNED INTEGER 类型的 taggable_id 列和一个 VARCHAR 类型的 taggable_type 列 |
| $table->multiLineString('positions'); | 等同于 MULTILINESTRING 类型列 |
| $table->multiPoint('positions'); | 等同于 MULTIPOINT 类型列 |
| $table->multiPolygon('positions'); | 等同于 MULTIPOLYGON 类型列 |
| $table->nullableMorphs('taggable'); | morphs() 列的 nullable 版本 |
| $table->nullableTimestamps(); | timestamps() 的别名 |
| $table->point('position'); | 等同于 POINT 类型列 |
| $table->polygon('positions'); | 等同于 POLYGON 类型列 |
| $table->rememberToken(); | 等同于添加一个允许为空的 remember_token VARCHAR(100) 列 |
| $table->smallIncrements('id'); | 等同于自增 UNSIGNED SMALLINT (主键)类型列 |
| $table->smallInteger('votes'); | 等同于 SMALLINT 类型列 |
| $table->softDeletes(); | 新增一个允许为空的 deleted_at TIMESTAMP 列用于软删除 |
| $table->softDeletesTz(); | 新增一个允许为空的 deleted_at TIMESTAMP (带时区)列用于软删除 |
| $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->timestamps(); | 添加允许为空的 created_at 和 updated_at TIMESTAMP 类型列 |
| $table->timestampsTz(); | 添加允许为空的 created_at 和 updated_at TIMESTAMP 类型列(带时区) |
| $table->tinyIncrements('numbers'); | 等同于自增的 UNSIGNED TINYINT 类型列(主键) |
| $table->tinyInteger('numbers'); | 等同于 TINYINT 类型列 |
| $table->unsignedBigInteger('votes'); | 等同于无符号的 BIGINT 类型列 |
| $table->unsignedDecimal('amount', 8, 2); | 等同于 UNSIGNED DECIMAL 类型列,带有总位数和精度 |
| $table->unsignedInteger('votes'); | 等同于无符号的 INTEGER 类型列 |
| $table->unsignedMediumInteger('votes'); | 等同于无符号的 MEDIUMINT 类型列 |
| $table->unsignedSmallInteger('votes'); | 等同于无符号的 SMALLINT 类型列 |
| $table->unsignedTinyInteger('votes'); | 等同于无符号的 TINYINT 类型列 |
| $table->uuid('id'); | 等同于 UUID 类型列 |
| $table->year('birth_year'); | 等同于 YEAR 类型列 |
列修改器
除上述数据列类型外,添加列时还可使用一些列“修改器”。例如,要使列允许为 NULL,可使用 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') | 添加注释信息 |
| ->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 方法允许将已存在的列修改为新类型或修改其属性。例如,若想增加字符串类型列的尺寸,可将 name 列的尺寸从 25 增加到 50:
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->change();
});
还可修改该列允许 NULL 值:
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->nullable()->change();
});
注:仅以下数据列类型能修改:bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger 和 unsignedSmallInteger。
重命名列
要重命名一个列,可使用表结构构建器上的 renameColumn 方法。在重命名列之前,确保 doctrine/dbal 依赖已添加到 composer.json 文件并已运行 composer update 命令:
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
注:暂不支持 enum 类型的列的修改和重命名。
删除数据列
要删除一个列,使用 Schema 构建器上的 dropColumn 方法。在此之前,确保已安装 doctrine/dbal 依赖:
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
可通过传递列名数组到 dropColumn 方法,以便一次从数据表中删除多个列:
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});
注:SQLite 数据库暂不支持在单个迁移中删除或修改多个列。
有效的命令别名
| 命令 | 描述 |
|---|---|
| $table->dropRememberToken(); | 删除 remember_token 列 |
| $table->dropSoftDeletes(); | 删除 deleted_at 列 |
| $table->dropSoftDeletesTz(); | dropSoftDeletes() 方法别名 |
| $table->dropTimestamps(); | 删除 created_at 和 updated_at 列 |
| $table->dropTimestampsTz(); | dropTimestamps() 方法别名 |
索引
创建索引
Schema 构建器支持多种类型的索引。首先,看一个指定列值为唯一索引的例子。要创建该索引,可使用 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) |
索引长度 & MySQL / MariaDB
Laravel 默认使用 utf8mb4 字符集,支持在数据库中存储 emoji 表情。若当前运行的 MySQL 版本低于 5.7.7(或 MariaDB 低于 10.2.2),需手动配置迁移命令生成的默认字符串长度,以便 MySQL 为它们创建索引。可通过在 AppServiceProvider 中调用 Schema::defaultStringLength 方法来完成配置:
use Illuminate\Support\Facades\Schema;
/**
* Bootstrap any application services.
*
* @return void
* @translator laravelacademy.org
*/
public function boot()
{
Schema::defaultStringLength(191);
}
作为可选方案,可为数据库启用 innodb_large_prefix 选项,至于如何合理启用这个选项,可参考数据库文档说明。
重命名索引
要重命名一个索引,可使用 renameIndex 方法,该方法接收当前索引名作为第一个参数以及修改后的索引名作为第二个参数:
$table->renameIndex('from', 'to')
删除索引
要删除索引,必须指定索引名。默认情况下,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) |
如果传递数据列数组到删除索引方法,那么相应的索引名称将会通过数据表名、列和键类型来自动生成:
Schema::table('geo', function (Blueprint $table) {
$table->dropIndex(['state']); // Drops index '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();
注:由于使用外键风险级联删除风险较高,一般情况下很少使用外键,而是通过代码逻辑来实现级联操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。