在 CentOS 系统中,要生成 Laravel 迁移文件,请按照以下步骤操作:
composer create-project --prefer-dist laravel/laravel your_project_name
将 your_project_name
替换为你的项目名称。
cd your_project_name
php artisan make:migration create_table_name_table
将 table_name
替换为你想要创建的表名。例如,如果你想要创建一个名为 users
的表,可以运行:
php artisan make:migration create_users_table
这将在 database/migrations
目录下生成一个新的迁移文件,文件名类似于 2021_06_01_000000_create_users_table.php
(时间戳可能会有所不同)。
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { 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(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
在 up()
方法中定义你的表结构,例如添加字段、设置数据类型等。在 down()
方法中定义如何回滚这个迁移,通常是删除刚刚创建的表。
保存文件后,运行以下命令应用迁移:
php artisan migrate
这将根据你在迁移文件中定义的表结构创建新的数据库表。
php artisan migrate:rollback
这将撤销最近的一次迁移。如果需要回滚多个迁移,可以使用 --step
选项指定回滚的迁移数量,例如:
php artisan migrate:rollback --step=2
这将回滚最近的两个迁移。