【问题标题】:How to get all children of a model through another model that has a many-to-many relationship?如何通过另一个具有多对多关系的模型来获取模型的所有孩子?
【发布时间】:2021-01-25 04:02:24
【问题描述】:

我有一个包含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);
    }

}

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

}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你试过了吗?

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

    【讨论】:

    • 是的,我试过了,但我得到:找不到列:1054 '字段列表'中的未知列'products.category_id' 这是因为 category_id 在类别模型中。类别和产品之间存在多对多关系。
    • 对不起,我很困惑,因为您的 Product 类有一个分类方法是 belongsTo()
    • 我认为您可能必须为 Category - SubProduct 使用另一个数据透视表并拥有另一个 belongsToMany(SubProduct::class)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2023-04-10
    • 2021-03-23
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多