首页 > 解决方案 > 如何通过另一个具有多对多关系的模型来获取模型的所有孩子?

问题描述

我有一个带有列的多级类别模型id, name, category_id

然后我有一个Product模型,它有很多SubProduct模型。

和模型CategoryProduct联结表具有多对多关系。

我对如何获得一个类别的所有子产品感到困惑。

如果我这样做:$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);
    }

}

产品.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');
    }

}

标签: laraveleloquent

解决方案


你试过这个吗?

class Category extends Model
{
    public function subProducts()
    {
        return $this->hasManyThrough(SubProduct::class, Product::class, 'category_id', 'product_id');
    }

}

推荐阅读