【发布时间】:2019-11-10 08:52:50
【问题描述】:
我正在做 Laravel 项目 我的项目中有多个级别的类别,我创建了一个方法来获取每个类别的所有产品及其子类别,所以问题是 products 是数组,我有很多问题,例如 pagination , where() , orderBy 和 ...
我想把我的方法改成更好的方法,我可以用它来解决上述问题
顺便说一句,我有一个方法名称 products(),它给出了所有类别的产品
这是我提供一系列产品的方法
public function getAllCategoriesProducts($cat_id){
$allProducts = [];
foreach(ProductCategory::find($cat_id)->products()->get() as $product){
$allProducts[] = $product;
}
foreach(ProductCategory::find($cat_id)->children()->get() as $subCategory){
if($subCategory->children()->exists()){
foreach($subCategory->children()->get() as $subSubCategory){
foreach($subSubCategory->products()->get() as $product){
$allProducts[] = $product;
}
}
if($subSubCategory->children()->exists()){
foreach($subSubCategory->children()->get() as $subSubSubCategory){
foreach($subSubSubCategory->products()->get() as $product){
$allProducts[] = $product;
}
if($subSubSubCategory->children()->exists()){
foreach($subSubSubCategory->children()->get() as $subSubSubSubCategory){
foreach($subSubSubSubCategory->products()->get() as $product){
$allProducts[] = $product;
}
}
}
}
}
}
}
return $allProducts;
}
【问题讨论】:
-
你为什么不使用 Laravel eloquent 的关系?
-
你为什么使用数组?您可以使用
collection而不是使用数组 -
@diego 当我想使用它时,我使用了 collect() 并且它更改为收集但不能正常工作
-
我正在尝试更正您的代码,但我不明白
if($subSubCategory->children()->exists())是什么,因为变量$subSubCategory不存在 -
@diego 现在运行良好,并为我提供了每个子类别的产品数组