简体   繁体   English

违反完整性约束 - Laravel

[英]Integrity constraint violation - Laravel

I am trying to create a relationship between categories and products.我正在尝试在类别和产品之间建立关系。 I have provided the various columns for both tables and I am trying to link them using a foreign id (the category_id from the category table) but I keep getting this error.我已经为这两个表提供了各个列,并且我正在尝试使用外部 ID(类别表中的 category_id)链接它们,但我一直收到此错误。

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails Integrity constraint violation: 1452 Cannot add or update a child row but it does not answer the question完整性约束违规:1452 无法添加或更新子行:外键约束失败完整性约束违规:1452 无法添加或更新子行但它没有回答问题

This is my Category table这是我的类别表

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

And this is the product table这是产品表

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('category_id');
        $table->string('name');
        $table->string('description');
        $table->string('image');
        $table->integer('price');
        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        $table->timestamps();
    });
}

This is the category model.这是类别 model。

class Category extends Model
{
 use HasFactory;

protected $fillable = [
    'name',
];


public function products()
{
    return $this->hasMany(Product::class);
}

} }

This is the product model这是产品 model

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'description',
        'image',
        'price',
        'category_id',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = $value * 100;
    }
}

This is my Product Factory class这是我的产品工厂 class

<?php
    
    namespace Database\Factories;
    
    use Illuminate\Database\Eloquent\Factories\Factory;
    
    class ProductFactory extends Factory
    {
       
        public function definition()
        {
            return [
                'name'=>$this->faker->unique()->word(),
                'description'=>$this->faker->text(),
                'image'=>$this->faker->imageUrl(100, 100),
                'price'=>$this->faker->numberBetween($min = 50, $max = 100),
                'category_id'=>$this->faker->randomDigit()
            ];
        }
    }

This is my db seeder class这是我的数据库播种机 class

class DatabaseSeeder extends Seeder

    {
       
        public function run()
        {
    
            Product::factory(20)->create();
        }
    }

This is the full error code I am getting please after running the db:seed这是我在运行 db:seed 后得到的完整错误代码

 INFO  Seeding database.  

Illuminate\Database\QueryException照亮\数据库\查询异常

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`econs`.`products`, CONSTRAINT `products_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) (SQL: insert into `products` (`name`, `description`, `image`, `price`, `category_id`, `updated_at`, `created_at`) values (omnis, Facere autem excepturi velit dolorem voluptas. Dignissimos laboriosam quia numquam sint harum officia eum. A aspernatur ratione fuga ut nesciunt sit. Ex nisi maxime quas., https://via.placeholder.com/100x100.png/006611?text=aut, 5700, 4, 2022-10-10 11:49:55, 2022-10-10 11:49:55))

  at vendor/Laravel/framework/src/Illuminate/Database/Connection.php:759
    755▕         // If an exception occurs when attempting to run a query, we'll format the error
    756▕         // message to include the bindings with SQL, which will make this exception a
    757▕         // lot more helpful to the developer instead of just the database's errors.
    758▕         catch (Exception $e) {
  ➜ 759▕             throw new QueryException(
    760▕                 $query, $this->prepareBindings($bindings), $e
    761▕             );
    762▕         }
    763▕     }

      +16 vendor frames 
  17  database/seeders/DatabaseSeeder.php:26
      Illuminate\Database\Eloquent\Factories\Factory::create()

      +23 vendor frames 
  41  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

You're using $this->faker->randomDigit() which creates a random digit, and doesn't care if the category ID exists or not.您正在使用$this->faker->randomDigit()创建一个随机数字,并且不关心类别 ID 是否存在。 For your factory, you can grab a random category and use it's id:对于您的工厂,您可以随机获取一个类别并使用它的 ID:

'category_id'=>Category::inRandomOrder()->first()->id
'category_id' => Category::inRandomOrder()->select("id")->first()->id ?? 1;

It will fetch only one category in random order.它只会以随机顺序获取一个类别。 After that give you the id attribute, If anything issue happens, then it will insert 1 as category id.之后给你 id 属性,如果发生任何问题,它会插入 1 作为类别 id。 But it will not through any exception.但它不会通过任何例外。

Try changing $table->unsignedInteger('category_id');尝试更改$table->unsignedInteger('category_id'); to $table->unsignedBigInteger('category_id');$table->unsignedBigInteger('category_id'); and also confirm that there is category id 4 present in Categories table并确认类别表中存在类别 ID 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM