1

I have the following migration (for a pivot table):

        Schema::create('category_news', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('news_id');

            $table->unique(['category_id', 'news_id']);

            $table->foreign('news_id')->references('id')->on('news')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });

I want to seed that table with some dummy data -- to do so, I have created the following factory:

$factory->define(CategoryNews::class, function (Faker $faker) {

  return [
    'category_id' => $faker->numberBetween($min = 1, $max = 35),
    'news_id' => $faker->numberBetween($min = 1, $max = 150)
  ];

});

However, when I run the following command: php artisan migrate:fresh --seed, I get the following error:

 Illuminate\Database\QueryException

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE) (SQL: insert into `category_news` (`category_id`, `news_id`, `updated_at`, `created_at`) values (16, 13, 2020-03-31 10:44:04, 2020-03-31 10:44:04))

  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[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE)")

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

Any idea why and what I need to do to fix it?

Thanks.

Moshe
  • 6,011
  • 16
  • 60
  • 112

2 Answers2

0

I figured it out -- I had to reorder my DatabaseSeeder.php file to call the NewsTableSeeder file before I called the CategoryNewsTableSeeder file.

Moshe
  • 6,011
  • 16
  • 60
  • 112
0

you are trying to add a new record category_news with category_id=16 while you don't have a category with id =16, so the constraint will throw an error ... you can't use random int to assign it to your foreign keys references ... you can simply do something like this:

$factory->define(CategoryNews::class, function (Faker $faker) {

  return [
    'category_id' => Category::all()->random()->id,
    'news_id' => News::all()->random()->id,
  ];
});

i have found this way here : https://stackoverflow.com/a/44102531/10573560

OMR
  • 11,736
  • 5
  • 20
  • 35