【问题标题】:Laravel: Error When Using a Factory for a Foreign KeyLaravel:使用工厂作为外键时出错
【发布时间】:2020-03-31 10:46:20
【问题描述】:

我有以下迁移(对于数据透视表):

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

我想在该表中植入一些虚拟数据——为此,我创建了以下工厂:

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

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

});

但是,当我运行以下命令时:php artisan migrate:fresh --seed,我收到以下错误:

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

知道为什么以及我需要做些什么来修复它吗?

谢谢。

【问题讨论】:

    标签: laravel laravel-6


    【解决方案1】:

    我想通了——我必须重新排序我的DatabaseSeeder.php 文件才能调用NewsTableSeeder 文件我调用CategoryNewsTableSeeder 文件之前。

    【讨论】:

      【解决方案2】:

      您正在尝试添加新记录 category_news,其中 category_id=16 虽然您没有 id = 16 的类别,但约束将引发错误... 您不能使用 random int 将其分配给您的外键引用... 你可以简单地做这样的事情:

      $factory->define(CategoryNews::class, function (Faker $faker) {
      
        return [
          'category_id' => Category::all()->random()->id,
          'news_id' => News::all()->random()->id,
        ];
      });
      

      我在这里找到了这种方式: https://stackoverflow.com/a/44102531/10573560

      【讨论】:

        猜你喜欢
        • 2021-04-25
        • 1970-01-01
        • 2019-06-21
        • 2017-06-19
        • 2015-12-02
        • 2021-02-21
        • 2021-02-21
        • 2020-10-06
        • 2014-04-03
        相关资源
        最近更新 更多