Laravel迁移可版本化管理数据库结构,通过Artisan命令创建、执行和回滚迁移文件,实现多环境结构同步;使用make:migration生成文件,up()定义变更、down()回滚,配合migrate等命令操作;结合Seeder填充测试数据,提升团队协作与部署稳定性。

Laravel 的数据库迁移(Migration)功能是管理数据库结构的利器,它让你像版本控制代码一样管理数据库变更。通过命令行创建和执行迁移文件,可以轻松在不同环境中同步表结构,避免手动修改带来的不一致问题。
使用 Artisan 命令快速生成迁移文件:
php artisan make:migration create_users_table
如果需要附带模式定义,可加上 --create 或 --table 参数:
php artisan make:migration create_posts_table --create=posts:会自动生成带有基础字段的骨架php artisan make:migration add_email_to_users_table --table=users:用于修改已有表每个迁移文件包含两个核心方法:up() 和 down()。
示例:创建 posts 表
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('posts');
}
迁移写好后,通过以下命令操作:
注意:生产环境慎用 refresh 和 fresh,建议配合备份策略。
迁移只管结构,数据填充可用 Seeder 配合完成。
php artisan make:seeder UserSeeder
php artisan db:seed 或指定类:php artisan db:seed --class=UserSeeder
可在 DatabaseSeeder 中调用多个 Seeder,形成初始化流程。
基本上就这些。合理使用 Migration 能大幅提升团队协作效率和部署稳定性,关键是保持迁移文件细粒度、语义清晰,并与实际发布节奏匹配。
以上就是Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号