Skip to content

迁移与填充

介绍

迁移是一种数据库版本控制工具。它们允许团队修改数据库架构并保持对当前架构状态的更新。迁移通常与架构构建器配对使用,以便轻松管理应用程序的架构。

创建迁移

要创建迁移,可以在 Artisan CLI 上使用 make:migration 命令:

php
php artisan make:migration create_users_table

迁移将被放置在 database/migrations 文件夹中,并包含一个时间戳,以便框架确定迁移的顺序。

--table--create 选项也可以用来指示表的名称,以及迁移是否将创建一个新表:

php
php artisan make:migration add_votes_to_users_table --table=users

php artisan make:migration create_users_table --create=users

运行迁移

运行所有未完成的迁移

php
php artisan migrate
lightbulb

如果在运行迁移时收到“类未找到”错误,请尝试运行 composer dump-autoload 命令。

在生产环境中强制迁移

某些迁移操作是破坏性的,可能会导致数据丢失。为了防止在生产数据库上运行这些命令,执行这些命令之前会提示确认。要在没有提示的情况下强制运行命令,请使用 --force 标志:

php
php artisan migrate --force

回滚迁移

回滚上一次迁移操作

php
php artisan migrate:rollback

回滚所有迁移

php
php artisan migrate:reset

回滚所有迁移并重新运行

php
php artisan migrate:refresh

php artisan migrate:refresh --seed

数据库填充

Laravel 还包括一种简单的方法来使用种子类填充测试数据。所有种子类都存储在 database/seeds 中。种子类可以有任何名称,但最好遵循一些合理的命名约定,例如 UserTableSeeder 等。默认情况下,为您定义了一个 DatabaseSeeder 类。通过这个类,您可以使用 call 方法运行其他种子类,从而控制填充顺序。

数据库种子类示例

php
class DatabaseSeeder extends Seeder {

	public function run()
	{
		$this->call('UserTableSeeder');

		$this->command->info('User table seeded!');
	}

}

class UserTableSeeder extends Seeder {

	public function run()
	{
		DB::table('users')->delete();

		User::create(['email' => 'foo@bar.com']);
	}

}

要填充数据库,可以在 Artisan CLI 上使用 db:seed 命令:

php
php artisan db:seed

默认情况下,db:seed 命令运行 DatabaseSeeder 类,该类可用于调用其他种子类。但是,您可以使用 --class 选项指定要单独运行的特定种子类:

php
php artisan db:seed --class=UserTableSeeder

您还可以使用 migrate:refresh 命令填充数据库,该命令还将回滚并重新运行所有迁移:

php
php artisan migrate:refresh --seed