【问题标题】:Laravel get all products from parent category or subcategory using eloquentLaravel 使用 eloquent 从父类别或子类别中获取所有产品
【发布时间】: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


    【解决方案1】:

    这样的事情可能就足够了。

    App\Models\Category::with('children', 'product_category.product')->get()
    

    建议,尝试实现pivot many to many relationship而不是这个product_category_mapping,然后模型关系会改变一点。

    对于pivot关系,需要修改Category模型

    public function products()
    {
      return $this->belongsToMany('App\Models\Product', 'product-category-mapping');
    }
    

    在产品模型中

    public function categories()
    {
        return $this->belongsToMany('App\Models\Category','product-category-mapping');
    }
    

    注意:这不是完整的集成,只是给你一个想法,完整的逻辑见https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

    【讨论】:

    • 使用“category_product”作为数据透视表会更好。但确实是唯一正确的方法。
    • @GertB。关于您的第一个解决方案产品类别详细信息将出现在子数组之外。所以我将循环结果以获取树结构。?
    • @GertB。如何获取单个类别(父)下的产品详细信息。在类别映射表中,类别 ID 可能是父 ID 或子 ID。请编辑您的答案。
    • 这不是我的答案,所以不,我不能编辑它:-D
    【解决方案2】:

    在您的产品模型中添加如下:

    public function product_categorys(){
    
        return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
    } 
    

    在控制器中你可以像这样Product::with('product_categorys')->get();

    【讨论】:

    • 解释你的答案。为什么你还在使用 hasMany? belongsToMany 将是一个简单的解决方案。旁注:拼写为“类别”,而不是“类别”
    • @Faran 如何获取单个类别(父类别)的详细信息..?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多