dongzhiju0324 2018-04-03 10:24
浏览 192
已采纳

Laravel 5.4:计算每个类别中的产品并按Eloquent查询对它们进行排序

I have two Models one is Product and the other is ProductCategory

and I have relations between both

Product Model

public function productCategory() {
        return $this->belongsTo( ProductCategory::class, 'product_category_id' );
    }

Product Category Model

public function categoryProduct() {
        return $this->hasMany( Product::class, 'product_category_id' );
    }

now each category has some product like (cat-1 has 3 products, cat-2 has 7 products, cat-3 has 5 products).

I need an Eloquent query which will get 4 categories sorted by the count of products in each category.

For Ex.

cat-2 has 7 products
cat-3 has 5 products
cat-1 has 3 products

tahnks

  • 写回答

3条回答 默认 最新

  • dounieqi6959 2018-04-03 10:32
    关注

    Use withCount() and then orderBy() to make it with single query.

    ProductCategory::with('categoryProduct')->withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
    

    To get just the count

    ProductCategory::withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型