首页 > 解决方案 > 如何在 Laravel 8 迁移期间将数据插入表中?

问题描述

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

标签: phpmysqllaravel

解决方案


先创建迁移

php artisan make:migration create_countries_table

create_countries_table

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

php artisan make:seeder CountriesTableSeeder

而在 国家/地区TableSeeder

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

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


有用的链接

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

推荐阅读