Moshe
Moshe

Reputation: 6991

Laravel: Migration & Seeding Problems

I am trying to seed a database and am getting an error when I run 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()

Here are the migration files:

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();
});

And here are the factory files:

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

And finally, here are the seed files:

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

// NewsSeeder and AuthorSeeder

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

Any idea why I am getting this error and what I can do to fix it?

Thanks.

Upvotes: 0

Views: 68

Answers (1)

Amjad
Amjad

Reputation: 374

simply because the migration file for news runs before authors

just try to change the timestamp for these two files to make authors migration run before news migration

Upvotes: 2

Related Questions