【问题标题】:How to change array with collection laravel如何使用集合 laravel 更改数组
【发布时间】: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 现在运行良好,并为我提供了每个子类别的产品数组

标签: php laravel


【解决方案1】:

【讨论】:

    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2017-03-07
    • 2020-06-29
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多