Laravel 8 迁移过程中如何向表中插入数据?

Iva*_*dez 1 php mysql laravel

我使用 Laravel 8 并使用 MYSQL 作为数据库,我必须创建一个国家/地区表,其中包含所有国家/地区名称作为“名称”列,世界上有 194 个国家/地区,我不想插入每个国家的名称一一对应,有什么简单的方法吗?

Abd*_*lam 6

首先创建迁移

php artisan make:migration create_countries_table
Run Code Online (Sandbox Code Playgroud)

在create_countries_table

public function up()
{
    Schema::create('countries', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });
}
Run Code Online (Sandbox Code Playgroud)

php artisan make:seeder CountriesTableSeeder
Run Code Online (Sandbox Code Playgroud)

国家TableSeeder

public function run()
{
    DB::table('countries')->insert(
        ['name' => 'Afghanistan'],
        ['name' => 'Albania']
        ....
    );
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用模型创建播种机Country::create(


有用的链接

  1. Laravel 8 数据库播种器教程:数据库播种器