属于Parent模型的三个模型的Laravel 8关系



大家好,我目前正在一个laravel项目中工作,我有一个父表,有三个表的id引用它。这些表迁移也有各自的模型。下面分别是表迁移文件:

create_products_table.php

Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_id', 10);
$table->string('product_name');
$table->string('image');
$table->string('images');
$table->string('product_description');
$table->bigInteger('size_id')->unsigned();
$table->string('color');
$table->string('product_quantity');
$table->string('old_price');
$table->string('discount');
$table->string('product_price');
$table->bigInteger('user_id')->unsigned()->nullable();
$table->bigInteger('category_id')->unsigned();
$table->bigInteger('gender_id')->unsigned();
$table->timestamps();
$table->foreign('size_id')->references('id')->on('sizes')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('genders')->onDelete('cascade');
});

create_genders_table.php

Schema::create('genders', function (Blueprint $table) {
$table->id();
$table->string('gender_class');
$table->timestamps();
});

create_categories_table.php

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

create_sizes_table.php

Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('sizes');
$table->timestamps();
});

这也是我如何分别定义它们模型上的关系

Product.php

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

public function gender()
{
return $this->belongsTo(Gender::class);
}

public function size()
{
return $this->belongsTo(Size::class);
}

Category.php

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

Gender.php

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

Size.php

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

我实际上是一个laravel.com的初学者,我在laravel.com上学习了雄辩的模型关系,所以我所做的只是基于我对一对多关系的理解。当我用dd($request)检查我的所有请求时,category_id, gender_id, size_id都显示为空,我相信这是因为我没有正确定义关系。现在我非常需要你的帮助。

所以请我的经验丰富的开发人员,我真的需要你的帮助,我真的很感激,如果我今天得到你的答复。提前谢谢。

=>Everything is right, just make changes in the products migration add this code.
$table->foreign('size_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('products')->onDelete('cascade');
=>and migrate table

最新更新