【问题标题】:how to optimize loop queries with laravel eloquent如何使用 laravel eloquent 优化循环查询
【发布时间】:2019-06-28 03:35:22
【问题描述】:

我正在尝试从我的数据库中获取“树视图”中的类别、子类别和产品。 我是 laravel 的新手,我不知道如何用雄辩的方法更好地编写这个动作。 我有 2 个表:产品和类别 每个产品都有 category_id 是类别表的外键

这是我的代码:

    $categories = Category::with('products')->where('id', $category->id)->get()->toArray();
    foreach ($categories as $key => $value) {

        $categories[$key]['children'] = Category::with('products')->where('parent_id', $value['id'])->get()->toArray();
    }

这是我的结果,很好

“结果”:[

    {
        "id": 2,
        "name": "Root 2",
        "parent_id": null,
        "products": [],
        "children": [
            {
                "id": 4,
                "name": "First child of Root 2",
                "parent_id": 2,
                "products": [
                    {
                        "id": 5,
                        "category_id": 4,
                        "name": "مهسا واثقی",
                        "description": "Aut eum et rerum dolorum blanditiis et itaque ipsum. Reiciendis consectetur magni est veritatis qui. Eos veniam quo aspernatur exercitationem vel incidunt. Rem aut sunt ab exercitationem.",
                        "price": "58.00",
                        "type": "video",
                        "disabled": 0,
                        "created_at": "2019-02-03 22:38:37",
                        "updated_at": "2019-02-03 22:38:37"
                    },
                ]
            },
            {
                "id": 5,
                "name": "Second child of Root 2",
                "parent_id": 2,
                "products": []
            },
            {
                "id": 6,
                "name": "Third child of Root 2",
                "parent_id": 2,
                "products": []
            }
        ]
    }
],

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以尝试使用递归关系,就像这样:

    public function childCategoriesRecursive()
    {
        return $this->hasMany(Category::class, 'id', 'parent_id')->with('childCategoriesRecursive');
    }
    

    当你加载这个新关系时,Laravel 会自动选择你所有的类别层次结构。那么你的代码应该是这样的:

        $categories = Category::with(['childCategoriesRecursive', 'products', 'childCategoriesRecursive.products'])->where('id', $category->id)->get()->toArray();
    

    现在,无需循环所有类别。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您可以使用“whereIn”代替循环中的查询。

      $categories = Category::with('products')->where('id', $category->id)->get()->toArray();
      $parentCategory = $categories->pluck('id');
      $categoriesObject = Category::with('products')->whereIn('parent_id', $parentCategory)->get()->toArray();
      foreach($categoriesObject as $key => $value){
       $childObject[$value->paernt_id][] = $value;
      }
      foreach($categories as $key => $value){
        $categories[$key]['child'] = isset($childObject[$value->id]) ? $childObject[$value->id] : [];
      }
      

      【讨论】:

      • 谢谢,但它不会返回父类别的名称和产品
      【解决方案3】:

      您可以通过以下方式使用递归函数

      $categories = Category::with('products')->where('id', $category->id)->get()->toArray();
      
      $categoriesWithChild = $this->GenerateCategoryArray($categories);
      dd($categoriesWithChild);
      

      在您的控制器中添加此功能:

      function GenerateCategoryArray($arr, $parent = null)
      {
          $pages = Array();
          foreach($arr as $page)
          {
             if($page['parent_id'] == $parent)
             {
                 $page['child'] = isset($page['child']) ? $page['child'] : $this->GenerateCategoryArray($arr, $page['id']);
                 $pages[] = $page;
              }
           }
            return $pages;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 2021-07-22
        • 2017-10-07
        • 2020-09-24
        • 2018-07-25
        • 2018-02-27
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        相关资源
        最近更新 更多