laravel-migrations

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel Migrations

Laravel 数据库迁移

Agent Workflow (MANDATORY)

Agent 工作流(强制要求)

Before ANY implementation, use
TeamCreate
to spawn 3 agents:
  1. fuse-ai-pilot:explore-codebase - Check existing migrations
  2. fuse-ai-pilot:research-expert - Verify Laravel 12 patterns via Context7
  3. mcp__context7__query-docs - Check specific Schema Builder features
After implementation, run fuse-ai-pilot:sniper for validation.

在进行任何实现之前,使用
TeamCreate
生成3个Agent:
  1. fuse-ai-pilot:explore-codebase - 检查现有迁移文件
  2. fuse-ai-pilot:research-expert - 通过Context7验证Laravel 12的开发模式
  3. mcp__context7__query-docs - 查阅Schema Builder的特定功能
完成实现后,运行fuse-ai-pilot:sniper进行验证。

Overview

概述

FeatureDescription
Schema BuilderCreate, modify, drop tables
Columns50+ column types with modifiers
IndexesPrimary, unique, fulltext, spatial
Foreign KeysConstraints with cascade options
SeedersPopulate tables with data

功能说明
Schema Builder创建、修改、删除表
50+种列类型及修饰符
索引主键、唯一、全文、空间索引
外键包含级联选项的约束
数据填充器为表填充测试或初始数据

Critical Rules

关键规则

  1. Always define down() - Reversible migrations
  2. Use foreignId()->constrained() - Not raw unsignedBigInteger
  3. Add indexes on foreign keys - Performance critical
  4. Test rollback before deploy - Validate down() works
  5. Never modify deployed migrations - Create new ones

  1. 必须定义down()方法 - 支持可逆迁移
  2. 使用foreignId()->constrained() - 不要使用原生unsignedBigInteger
  3. 为外键添加索引 - 对性能至关重要
  4. 部署前测试回滚 - 验证down()方法可用
  5. 切勿修改已部署的迁移文件 - 应创建新的迁移文件

Decision Guide

决策指南

Migration Type

迁移类型

Need schema change?
├── New table → make:migration create_X_table
├── Add column → make:migration add_X_to_Y_table
├── Modify column → make:migration modify_X_in_Y_table
├── Add index → make:migration add_index_to_Y_table
└── Seed data → make:seeder XSeeder
需要修改架构?
├── 新建表 → make:migration create_X_table
├── 添加列 → make:migration add_X_to_Y_table
├── 修改列 → make:migration modify_X_in_Y_table
├── 添加索引 → make:migration add_index_to_Y_table
└── 填充数据 → make:seeder XSeeder

Column Type Selection

列类型选择

Use CaseTypeExample
Primary Key
id()
Auto-increment BIGINT
Foreign Key
foreignId()->constrained()
References parent
UUID Primary
uuid()->primary()
UUIDs
Boolean
boolean()
is_active
Enum
enum('status', [...])
order_status
JSON
json()
preferences
Money
decimal('price', 10, 2)
99999999.99
Timestamps
timestamps()
created_at, updated_at
Soft Delete
softDeletes()
deleted_at
使用场景类型示例
主键
id()
自增BIGINT
外键
foreignId()->constrained()
关联父表
UUID主键
uuid()->primary()
UUID标识符
布尔值
boolean()
is_active
枚举
enum('status', [...])
order_status
JSON类型
json()
preferences
金额
decimal('price', 10, 2)
99999999.99
时间戳
timestamps()
created_at, updated_at
软删除
softDeletes()
deleted_at

Foreign Key Cascade

外键级联选项

ScenarioonDeleteUse Case
Strict integrity
restrictOnDelete()
Financial records
Auto-cleanup
cascadeOnDelete()
Post → Comments
Preserve with null
nullOnDelete()
Optional relations
No action
noActionOnDelete()
Audit logs

场景onDelete 选项适用案例
严格数据完整性
restrictOnDelete()
财务记录
自动清理关联数据
cascadeOnDelete()
文章 → 评论
保留数据并设为null
nullOnDelete()
可选关联关系
无操作
noActionOnDelete()
审计日志

Reference Guide

参考指南

Core Concepts

核心概念

TopicReferenceWhen to Consult
Schemaschema.mdTable operations
Columnscolumns.mdColumn types
Indexesindexes.mdPerformance indexes
Foreign Keysforeign-keys.mdConstraints
Commandscommands.mdArtisan commands
Seedingseeding.mdPopulate data
主题参考文档查阅场景
Schemaschema.md表操作相关
columns.md列类型选择
索引indexes.md性能优化索引
外键foreign-keys.md约束配置
命令commands.mdArtisan命令使用
数据填充seeding.md数据填充操作

Advanced Topics

进阶主题

TopicReferenceWhen to Consult
Testingtesting.mdTest migrations
Productionproduction.mdDeploy safely
Troubleshootingtroubleshooting.mdFix errors
主题参考文档查阅场景
测试testing.md迁移测试
生产环境production.md安全部署
故障排查troubleshooting.md错误修复

Templates

模板

TemplateWhen to Use
CreateTableMigration.php.mdNew table
ModifyTableMigration.php.mdAlter table
PivotTableMigration.php.mdMany-to-many
Seeder.php.mdSeed patterns
MigrationTest.php.mdTest migrations

模板使用场景
CreateTableMigration.php.md新建表
ModifyTableMigration.php.md修改表
PivotTableMigration.php.md多对多关联表
Seeder.php.md数据填充器模板
MigrationTest.php.md迁移测试模板

Quick Reference

快速参考

Create Table

创建表

php
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title');
    $table->text('content');
    $table->enum('status', ['draft', 'published'])->default('draft');
    $table->timestamps();
    $table->softDeletes();

    $table->index(['user_id', 'status']);
});
php
Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title');
    $table->text('content');
    $table->enum('status', ['draft', 'published'])->default('draft');
    $table->timestamps();
    $table->softDeletes();

    $table->index(['user_id', 'status']);
});

Modify Table

修改表

php
Schema::table('posts', function (Blueprint $table) {
    $table->string('slug')->after('title')->unique();
    $table->boolean('featured')->default(false);
});
php
Schema::table('posts', function (Blueprint $table) {
    $table->string('slug')->after('title')->unique();
    $table->boolean('featured')->default(false);
});

Commands

命令

bash
php artisan make:migration create_posts_table
php artisan migrate
php artisan migrate:rollback --step=1
php artisan migrate:fresh --seed

bash
php artisan make:migration create_posts_table
php artisan migrate
php artisan migrate:rollback --step=1
php artisan migrate:fresh --seed

Best Practices

最佳实践

DO

建议

  • Use
    foreignId()->constrained()
    for foreign keys
  • Add composite indexes for common queries
  • Test down() method before deploying
  • Use
    --pretend
    to preview SQL
  • 使用
    foreignId()->constrained()
    定义外键
  • 为常用查询添加复合索引
  • 部署前测试down()方法
  • 使用
    --pretend
    参数预览SQL语句

DON'T

不建议

  • Modify already-deployed migrations
  • Forget down() method
  • Use raw SQL without Schema Builder
  • Skip indexes on foreign keys
  • 修改已部署的迁移文件
  • 遗漏down()方法
  • 绕过Schema Builder直接使用原生SQL
  • 不为外键添加索引