首页 > 解决方案 > Laravel:迁移和播种问题

问题描述

我正在尝试为数据库播种,但在运行时出现错误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();

知道为什么我会收到此错误以及我可以做些什么来解决它吗?

谢谢。

标签: laravellaravel-6

解决方案


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

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


推荐阅读