【发布时间】:2021-01-25 04:02:24
【问题描述】:
我有一个包含id, name, category_id 列的多级类别模型
然后我有一个Product 模型,其中有许多SubProduct 模型。
Category 和 Product 模型与联结表具有多对多关系。
我对如何获取某个类别的所有子产品感到困惑。
如果我这样做:$category->products[0]->childProducts; 我能够获得所有子产品,但是我想要一种方法来做到这一点,而无需索引产品并获得所有类别产品。
我的模型代码如下:
Category.php(注意我用 hasManyThrough 创建了一个 subProducts 函数,但它的用法可能不正确?)
class Category extends Model
{
// Get the sub categories for the category.
public function categories()
{
return $this->hasMany(Category::class, 'category_id');
}
// Get the parent category that owns the category.
public function parent()
{
return $this->belongsTo(Category::class, 'category_id');
}
// Get the products
public function products()
{
return $this->belongsToMany(Product::class);
}
public function subProducts()
{
return $this->hasManyThrough(SkuProduct::class, Product::class);
}
}
Product.php
class Product extends Model
{
public function childProducts()
{
return $this->hasMany(SubProduct::class, 'product_id');
}
/**
* Get the category that owns the product.
*/
public function category()
{
return $this->belongsTo(Category::class);
}
}
子产品.php
class SubProduct extends Mode
{
public function parentProduct()
{
return $this->belongsTo(Product::class, 'product_id');
}
}
【问题讨论】: