【问题标题】:Laravel Eloquent query recursive relationship model with paginationLaravel Eloquent 带分页的查询递归关系模型
【发布时间】:2021-01-16 10:17:04
【问题描述】:

我正在建立一个商店,我必须向用户显示给定类别中的所有产品以及当前访问的后续子类别中包含的所有其他产品。类别有 N+1 问题,因为可以有无限的子类别。我希望能够过滤这些产品并能够对它们进行分页。 这是我的类别模型:

   class CatalogCategory extends Model
   {

    public function parent()
    {
        return $this->belongsTo('App/CatalogCategory','parent_id');
    }

    public function children()
    {
        return $this->hasMany($this,'parent_id')
            ->orderBy('order_place','ASC')
            ->with('children');
    }

    /*
    *   Return products, that belong just to the parent category.
    */

    public function products()
    {
        return $this->hasMany('App\CatalogProduct','parent_id')
            ->where('is_active', 1)
            ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
            ->orderBy('created_at','DESC');
    }

    /*
    *   Return all products contained in the parent category and its children categories.
    */

    public function all_products()
    {
        $products = $this->products;

        foreach ($this->children as $child) {
            $products = $products->merge($child->all_products());
        }

        return $products;
    }

}

all_products() 方法返回我想要的所有产品,但由于它是一个集合,我无法对其进行分页或过滤。我的问题是是否有更好的方法来检索产品以及如何检索它们,以便我可以查询它们以进行过滤和分页?

【问题讨论】:

  • 你不能在控制器中运行这个查询吗????
  • 这是我的问题,我如何查询递归关系以获取该类别和后续子类别中的所有产品,但能够对它们进行分页和过滤
  • 查看github.com/staudenmeir/laravel-adjacency-list,该包创建了允许递归查找的 CTE 查询。

标签: php laravel recursion laravel-5 eloquent


【解决方案1】:

您可以使用嵌套集技术来存储类别。

嵌套集技术允许在一个查询中检索层次结构中某个节点的所有后代或祖先。

你可以试试这个包:https://github.com/lazychaser/laravel-nestedset。恕我直言,这是 laravel 中嵌套集的最佳实现。

安装和配置将花费您 10 分钟。

之后,您可以像这样检索您的产品:

public function products($slug) 
{
    //first query: retrieving current category
    $category = CatalogCategory
        ::where('slug', $slug)
        ->first();
    
    //second query: retrieving all category descendants and self ids.
    $categoryIds = $category
        ->descendants
        ->pluck('id')
        ->push($category->id);

    //third query: retrieving all products.
    $products = CatalogProduct
        ::whereIn('parent_id', $categoryIds)
        ->where('is_active', 1)
        ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
        ->orderBy('created_at', 'desc');
        ->paginate(50);

    return view('path_to_view', compact('products', 'category'));
}

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 2019-09-16
    • 2013-10-03
    • 2017-07-19
    • 2016-01-16
    • 2021-08-27
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多