【发布时间】: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