Laravel: проблемы с миграцией и посевом - PullRequest
0 голосов
/ 27 марта 2020

Я пытаюсь заполнить базу данных и получаю сообщение об ошибке при запуске 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 Ответ

2 голосов
/ 27 марта 2020

просто потому, что файл миграции для news запускается до authors

, просто попробуйте изменить временную метку для этих двух файлов, чтобы authors запустить миграцию до news миграции

...