Laravel 5数据库迁移(Migrations)使用指南
数据库迁移(Database Migrations)是 Laravel 框架中极具威力的特性之一。你可以将其概念化为数据库架构的版本控制系统,便于追踪和管理结构变更。
在 database/migrations 目录下默认存在两个迁移文件:一个负责创建用户表,另一个则用于支持用户密码重置功能。
在每个迁移文件中,up 方法定义了创建数据表的逻辑,而 down 方法则定义了回滚操作,即删除相应数据表。
执行数据库迁移
复制代码 代码如下: php artisan migrate #输出 Migration table created successfully. Migrated: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_100000_create_password_resets_table
检查 MySQL 数据库可以发现生成了三张表:migrations 表用于记录迁移历史,此外还有 users 和 password_resets 两张业务表。
如果在设计过程中发现错误,可以通过执行数据库回滚来撤销更改。
复制代码 代码如下: php artisan migrate:rollback #输出 Rolled back: 2014_10_12_100000_create_password_resets_table Rolled back: 2014_10_12_000000_create_users_table
再次查看 MySQL 数据库,此时仅保留 migrations 表,之前创建的 users 和 password_resets 表已被成功删除。
若要修正迁移文件中的定义,修改后可再次执行迁移操作以应用新的结构。
新建迁移
复制代码 代码如下: php artisan make:migration create_article_table --create='articles' #输出 Created Migration: 2026_03_28_050138_create_article_table
该命令会在 database/migrations 目录下生成一个新的迁移文件。
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('articles');
}
}
系统自动添加了自增的 id 列,以及 timestamps() 方法生成的 created_at 和 updated_at 时间戳字段。在此基础上,我们可以进一步添加其他所需字段:
public function up()
{
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamp('published_at');
$table->timestamps();
});
}
执行迁移:
复制代码 代码如下: php artisan migrate
此时数据库中已出现新的 articles 数据表。
假设需要为现有表添加新字段,可以选择先回滚,修改迁移文件后再重新执行迁移;也可以直接创建一个新的迁移文件来处理变更。
复制代码 代码如下: php artisan make:migration add_excerpt_to_articels_table
查看新生成的迁移文件内容。
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddExcerptToArticelsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
初始状态下,up 和 down 方法均为空。虽然可以手动编写代码,但 Laravel 提供了更便捷的方式:删除当前文件并重新生成,同时传入 --table 参数以获取针对特定表的模板代码。
复制代码 代码如下: php artisan make:migration add_excerpt_to_articels_table --table='articles'
现在,up 方法内部已经包含了针对 articles 表的初始化代码框架。
public function up()
{
Schema::table('articles', function(Blueprint $table)
{
//
});
}
接下来添加实际的数据修改逻辑代码:
public function up()
{
Schema::table('articles', function(Blueprint $table)
{
$table->text('excerpt')->nullable();
});
}
public function down()
{
Schema::table('articles', function(Blueprint $table)
{
$table->dropColumn('excerpt');
});
}
nullable() 方法表明该字段允许存储 NULL 值。
再次执行迁移命令并检查数据库验证结果。
为了演示效果,我们尝试执行一次回滚操作。
复制代码 代码如下: php artisan migrate:rollback
此时 excerpt 列已从表中移除。
以上内容涵盖了 Laravel 5 数据库迁移的核心操作流程,希望能帮助读者熟练掌握该框架的这一重要功能。