【发布时间】:2022-02-17 16:37:45
【问题描述】:
我想检索所选父类别的所有产品。产品模型与 product_category_mapping 表有很多关系。
如果产品有类似的子类别结果,
"MAinCatergory":[
{
id="",
name:"Drinks",
"ChildCategory":[
{
"id":1,
"name":"Juce",
"Products":[{
name:"apple juce",
price:10,
....
}]
}
]
}
]
}
如果主类别下的产品只返回数组,
"MAinCatergory":[
{
id="",
name:"Drinks",
"Products":[{
name:"apple juce",
price:10,
....
}]
}
}
]
}
类别表字段 - id,name,parent_id
产品表字段 - id、名称、价格、..、
产品类别映射表字段 - id,category_id,product_id
类别模型
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function product_category()
{
return $this->hasMany('App\Models\ProductCategoryMapping', 'category_id');
}
产品型号
public function product_category()
{
return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
}
产品类别映射
public function product()
{
return $this->belongsTo(Product::class,'product_id','id');
}
public function category()
{
return $this->belongsTo(Category::class,'category_id','id');
}
【问题讨论】:
标签: laravel