Laravel从无限嵌套类别中获取所有产品 [英] Laravel get all products from infinity nested categories

查看:37
本文介绍了Laravel从无限嵌套类别中获取所有产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别模型,其中每个类别都可以是通用类别或嵌套类别.

I have the category model where each category can be general or nesting.

类别: ID parent_id 标题

Category: id parent_id title

要获取类别的子级和所有嵌套的类别的子级,请使用递归关系

To get children of category and all nested children of category use relation with recursion

public function children()
{
    return $this->hasMany('App\Models\Category', 'parent_id', 'id');
}

public function allChildren()
{
    return $this->children()->with('allChildren');
}

与产品的关系

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

如何从基本类别和所有嵌套类别中获取所有产品?

How can I get all products from base category and all nested categories?

推荐答案

如果您不关心性能,这样的东西应该可以工作(未经测试),但是如果您有非常复杂的类别树,它显然会产生很多查询

If you don't care about performance something like this should work (not tested) but it might obviously generate many queries in case you have very complex tree of categories.

$products = Category::getAllProducts($categoryId);

public static function getAllProducts($categoryId, $products = null)
{
  if ($products === null) {
     $products = collect();   
  }
  $category = Category::find($categoryId); 
  $products = $products->merge($category->product);
  $category->children->each(function($child) {
      $products = self::getAllProducts($child->id, $products);
  });

  return $products;
}

或者,您可以首先找到所有类别,然后找到属于那些类别的产品,并假设您不会获得数百个类别,因为如果不使用原始查询,可能会导致PDO绑定问题.

As alternative you could find first all the categories and then products that belong to those categories assuming you won't get hundreds of categories because it could lead to PDO bindings problems if you don't use raw queries.

这篇关于Laravel从无限嵌套类别中获取所有产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆