Laravel:迁移和播种问题

时间:2020-03-26 21:32:56

标签: laravel laravel-6

我正在尝试播种数据库,并且在运行php artisan migrate:fresh时遇到错误:

 Illuminate\Database\QueryException

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `news` add constraint `news_author_id_foreign` foreign key (`author_id`) references `authors` (`id`) on delete cascade)

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

  2   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOStatement::execute()

以下是迁移文件:

Schema::create('news', function (Blueprint $table) {
  $table->bigIncrements('id');
   ...
  $table->unsignedBigInteger('author_id');
  $table->foreign('author_id')
    ->references('id')
    ->on('authors')
    ->onDelete('cascade');
});
Schema::create('authors', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

这是工厂文件:

$factory->define(Author::class, function (Faker $faker) {
    return [
        'name' => $faker->name
    ];
});
    return [
      ...
      'author_id' => $faker->numberBetween($min = 1, $max = 50),
    ];

最后,这是种子文件:

// DatabaseSeeder
    {
        $this->call(AuthorsTableSeeder::class);
        $this->call(NewsTableSeeder::class);
    }

// NewsSeeder and AuthorSeeder

factory(App\News::class, 150)->create();
factory(App\Authors::class, 50)->create();

有人知道为什么我会收到此错误以及如何解决该错误吗?

谢谢。

1 个答案:

答案 0 :(得分:2)

仅仅是因为news的迁移文件在authors之前运行

只需尝试更改这两个文件的时间戳,以使authors迁移在news迁移之前进行