Laravel迁移后添加数据导致错误

时间:2020-01-12 06:59:42

标签: php laravel

我想在refreshdatabase migration

之后添加这些数据
public function up()
    {
        Schema::create('locations', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('type');
            $table->integer('pid')->default(0);
            $table->integer('cid')->default(0);
            $table->string('name');
            $table->timestamps();
        });

        DB::table('locations')->insert([
            ['type' => 1, 'name' => 'Istanbul'],
            ['type' => 2, 'name' => 'Istanbul', 'pid' => 1],
            ['type' => 3, 'name' => 'Taksim', 'cid' => 2],
            ['type' => 3, 'name' => 'Beyoglu', 'cid' => 2],
        ]);
    }

但是它给了我这个错误:

?[41; 1m Illuminate \ Database \ QueryException?[49; 22m: [33mSQLSTATE [42S01]:基本表或视图已存在:1050表 “位置”已存在(SQL:创建表locationsid bigint unsigned not null null auto_increment主键,type int not null,pid int不为null的默认值'0',cid int不为null的默认值'0', name varchar(255)不为空,created_at时间戳为空, updated_at ti mestamp null)默认字符集utf8mb4整理 'utf8mb4_unicode_ci')

我该如何解决?

1 个答案:

答案 0 :(得分:1)

从迁移中删除DB:table并运行:

php artisan migrate:refresh

然后

php artisan make:seed LocationTableSeeder

然后将其添加到run()函数中:

    DB::table('locations')->insert([
        ['type' => 1, 'name' => 'Istanbul', 'pid' => 0, 'cid' => 0, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')],
        ['type' => 2, 'name' => 'Istanbul', 'pid' => 1, 'cid' => 0, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')],
        ['type' => 3, 'name' => 'Taksim', 'cid' => 2, 'pid' => 0, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')],
        ['type' => 3, 'name' => 'Beyoglu', 'cid' => 2, 'pid' => 0, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')],
    ]);

然后

php artisan db:seed --class=LocationTableSeeder
相关问题