【发布时间】:2021-11-18 16:15:30
【问题描述】:
大家好,我目前正在从事一个 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();
});
这也是我分别在他们的模型上定义关系的方式
产品.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);
}
性别.php
public function products()
{
return $this->hasMany(Product::class);
}
大小.php
public function products()
{
return $this->hasMany(Product::class);
}
我实际上是一个 laravel 初学者,我在 laravel.com 研究了雄辩的模型关系,所以我所做的只是基于我对一对多关系的理解。当我用 dd($request) 检查我的所有请求时,category_id、gender_id、size_id 都显示为 null,我相信这是因为我没有正确定义关系。现在,我非常需要您的帮助。
请各位经验丰富的开发人员帮忙,我非常需要您的帮助,如果今天能收到您的回复,我将不胜感激。提前致谢。
【问题讨论】:
-
查看预加载,特别是它引用“with”laravel.com/docs/8.x/eloquent-relationships#eager-loading
标签: php mysql database laravel eloquent