laravel 推荐用 add_字段名_to_表名_table 命名迁移文件,自动识别表与操作;up() 中用 schema::table() 添加字段并注意外键、nullable、数据库兼容性;down() 需手动对称回滚,先删外键再删字段;务必提交迁移文件并避免直连数据库改结构。

php artisan make:migration add_xxx_to_yyy_table 生成迁移文件
执行命令时,add_字段名_to_表名_table 是 Laravel 官方推荐的命名约定,Laravel 能据此自动识别要操作的表和动作。比如给 users 表加 phone 字段,运行:
php artisan make:migration add_phone_to_users_table
生成的文件名类似 2024_05_20_103022_add_phone_to_users_table.php,其中时间戳保证执行顺序。
注意:别手写文件名或手动改时间戳——Laravel 依赖它做迁移顺序管理;也别用 create_users_table 这类名字来新增字段,那会被当成建新表处理。
在 up() 中用 table() 方法修改已有表
新增字段必须在 up() 方法里调用 Schema::table(),不是 Schema::create()。后者只用于建表,对已存在表执行会报错 SQLSTATE[42S01]: Base table or view already exists。
table() 的第二个参数是闭包,里面用 $table->xxxColumn() 添加字段:
public function up(MigrationBuilder $migration)
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable()->after('email');
$table->unsignedBigInteger('company_id')->nullable();
$table->foreign('company_id')->references('id')->on('companies');
});
}
常见易错点:
-
after('xxx')只在 MySQL 有效,SQLite 和 PostgreSQL 不支持,上线前务必确认数据库类型 - 外键字段必须和被引用字段类型严格一致(比如都是
unsignedBigInteger),否则foreign()会静默失败或报错 - 如果字段允许为空,一定要显式写
nullable();Laravel 默认字段是NOT NULL
down() 必须与 up() 逻辑对称
回滚不是“删掉迁移文件”或者“忽略”,而是靠 down() 执行逆向操作。Laravel 不会自动推断怎么撤回,你得手动写清楚:
public function down(MigrationBuilder $migration)
{
Schema::table('users', function (Blueprint $table) {
$table->dropForeign(['company_id']);
$table->dropColumn(['phone', 'company_id']);
});
}
关键规则:
- 删除外键必须先于删除字段,否则 MySQL 报错
Cannot drop index 'xxx': needed in a foreign key constraint -
dropColumn()接收数组或字符串,但一次只能删一个外键约束,多个需分多行调用dropForeign() - 如果
up()里加了索引(如$table->index('phone')),down()里也要对应$table->dropIndex('users_phone_index')
执行迁移前先检查 schema 文件是否已提交
多人协作时,常有人本地跑过 migrate 但忘了提交新生成的迁移文件,结果其他人 git pull 后直接 php artisan migrate,Laravel 会跳过这个文件(因记录在 migrations 表中),导致字段缺失且无提示。
稳妥做法:
- 每次
git status确认新迁移文件已加入暂存区 - 上线前在测试环境完整跑一遍
php artisan migrate:fresh --seed(开发机慎用) - 生产环境避免用
migrate:refresh,优先用单条migrate+ 手动验证字段是否存在
最麻烦的情况是字段已加但没走迁移流程——比如直接进数据库执行 ALTER TABLE,后续再跑迁移会冲突。这种状态很难自动修复,得人工比对 migrations 表和实际表结构。











