我有两个模型
,一个是Product
,另一个是ProductCategory
我和两者之间有关系
产品型号
public function productCategory() {
return $this->belongsTo( ProductCategory::class, 'product_category_id' );
}
产品类别模型
public function categoryProduct() {
return $this->hasMany( Product::class, 'product_category_id' );
}
现在每个类别都有一些产品,例如(cat-1 有 3 个产品,cat-2 有 7 个产品,cat-3 有 5 个产品)
。
我需要一个 Eloquent 查询
,它将获得 4 个类别,这些类别按每个类别中的产品数量排序。
例如
cat-2 has 7 products
cat-3 has 5 products
cat-1 has 3 products
谢谢
最佳答案
使用withCount()然后 orderBy()用单个
查询来实现。
ProductCategory::with('categoryProduct')->withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
为了得到计数
ProductCategory::withCount('categoryProduct')->orderBy('category_product_count','desc')->get();
关于php - 拉维尔 5.4 : count the products in each category and sort them by Eloquent query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49627696/