Linux环境下 Laravel 数据库迁移指南
一 环境准备与项目初始化
php -v、composer --version 验证版本。composer global require laravel/installerlaravel new your_project_name 或 composer create-project --prefer-dist laravel/laravel your_project_namecd your_project_name二 迁移全流程与常用命令
php artisan make:migration create_users_table --create=usersphp artisan make:migration add_votes_to_users_table --table=usersdatabase/migrations/xxxx_create_xxx_table.php 的 up() 中定义结构,down() 中编写回滚逻辑(成对可逆)。php artisan migrate(按时间戳顺序执行未运行迁移,并在数据库中维护 migrations 表记录)。php artisan migrate:rollbackphp artisan migrate:rollback --step=Nphp artisan migrate:resetphp artisan migrate:refresh(开发环境常用,生产慎用)php artisan make:seeder UsersTableSeederphp artisan db:seed --class=UsersTableSeeder 或全量 php artisan db:seed三 常见迁移操作示例
php artisan make:migration create_users_table --create=usersup() 中使用 Schema::create('users', function (Blueprint $table) { ... }),常见字段:$table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps();down() 中 Schema::dropIfExists('users');php artisan make:migration add_phone_to_users_table --table=usersSchema::table('users', function (Blueprint $table) { $table->string('phone')->nullable(); $table->after('email'); });composer require doctrine/dbalSchema::table('users', function (Blueprint $table) { $table->string('name', 100)->change(); $table->text('bio')->nullable()->change(); });Schema::rename('old_table', 'new_table');Schema::table('users', function (Blueprint $table) { $table->renameColumn('old_name', 'new_name'); });$table->index('user_id'); $table->unique('slug'); $table->fullText('content');$table->foreignId('user_id')->constrained()->onDelete('cascade');$table->dropIndex(['user_id']); $table->dropUnique(['slug']); $table->dropForeign(['user_id']);DB::statement('ALTER TABLE users ADD COLUMN points INT DEFAULT 0;');(在 down() 中编写对应回滚语句)四 生产环境注意事项与故障排查
migrate:refresh、migrate:reset 等会丢失数据的命令;上线前在预备环境演练,并做好 全量备份。down() 中回滚;必要时手动清理或新建修正迁移。