laravel 迁移是管理数据库架构更改的好方法。它们允许您对数据库结构进行版本控制,并随时间轻松回滚或修改更改。在本指南中,我们将逐步探索在 laravel 中创建、运行和回滚迁移的过程,并提供一个实践示例。
开始迁移之前,请确保已安装 laravel。您可以通过 composer 执行此操作:
composer create-project --prefer-dist laravel/laravel migration-demo
然后导航到项目文件夹:
cd migration-demo
要配置数据库,请在 laravel 项目中打开 .env 文件并更新数据库凭据:
db_connection=mysql db_host=127.0.0.1 db_port=3306 db_database=your_database_name db_username=your_username db_password=your_password
配置数据库后,如果本地环境尚不存在,您可以创建一个新数据库。
您可以使用 artisan 命令创建新的迁移。例如,要创建用户表迁移:
php artisan make:migration create_users_table
该命令在database/migrations目录中生成一个迁移文件。文件名将包含时间戳,类似于 2024_09_13_123456_create_users_table.php。
打开生成的迁移文件。你会发现两个方法:up()(定义表创建)和down()(定义表如何回滚)。
创建用户表的示例:
<?php use illuminatedatabasemigrationsmigration; use illuminatedatabaseschemablueprint; use illuminatesupportfacadesschema; class createuserstable extends migration { /** * run the migrations. * * @return void */ public function up() { schema::create('users', function (blueprint $table) { $table->id(); // primary key $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->remembertoken(); $table->timestamps(); // created at & updated at }); } /** * reverse the migrations. * * @return void */ public function down() { schema::dropifexists('users'); } }
在 up() 方法中,我们定义了 users 表的结构。 down() 方法定义了在回滚时如何删除表(即删除表)。
要运行迁移并在数据库中创建用户表,请使用以下命令:
php artisan migrate
此命令将执行所有尚未运行的迁移。您应该看到以下输出:
migrating: 2024_09_13_123456_create_users_table migrated: 2024_09_13_123456_create_users_table (0.45 seconds)
您可以验证用户表是否已在数据库中创建。
要回滚最近的迁移,请使用以下命令:
php artisan migrate:rollback
这将删除用户表或最近迁移批次中定义的任何表。
要回滚多个个迁移步骤,请使用:
php artisan migrate:rollback --step=2
这将回滚最后两批迁移。
如果要修改现有表(例如添加列),请创建新的迁移:
php artisan make:migration add_phone_to_users_table --table=users
这将创建一个用于修改用户表的迁移。然后您可以定义更改:
public function up() { schema::table('users', function (blueprint $table) { $table->string('phone')->nullable(); // add phone column }); } public function down() { schema::table('users', function (blueprint $table) { $table->dropcolumn('phone'); // remove phone column }); }
运行迁移以应用更改:
php artisan migrate
laravel 还允许您使用虚拟数据为数据库播种。要创建播种机,请使用:
php artisan make:seeder userstableseeder
在位于database/seeders/userstableseeder.php的播种器文件中,您可以定义数据:
use illuminatesupportfacadesdb; use illuminatesupportfacadeshash; class userstableseeder extends seeder { public function run() { db::table('users')->insert([ 'name' => 'john doe', 'email' => 'john@example.com', 'password' => hash::make('password'), ]); } }
然后使用以下命令运行播种器:
php artisan db:seed --class=userstableseeder
您还可以在迁移过程中通过调用 databaseseeder.php 中的播种器来为数据库播种。
重置数据库并运行所有迁移和播种程序:
php artisan migrate:fresh --seed
此命令将删除所有表,重新运行所有迁移,并为数据库设定种子。
通过执行以下步骤,您可以使用迁移轻松管理 laravel 中的数据库架构更改。 laravel 迁移是保持数据库结构版本控制并在不同环境(如开发、登台和生产)之间同步的重要组成部分。