我有两个Models,一个是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 has 3 products, cat-2 has 7 products, cat-3 has 5 products)的产品。
我需要一个Eloquent query,这将得到4个类别,按计数的产品在每个类别。
为了快递。
cat-2 has 7 products
cat-3 has 5 products
cat-1 has 3 products金克
发布于 2018-04-03 10:32:15
使用withCount(),然后使用orderBy()来使用single查询。
ProductCategory::with('categoryProduct')->withCount('categoryProduct')->orderBy('category_product_count','desc')->get();才能拿到伯爵
ProductCategory::withCount('categoryProduct')->orderBy('category_product_count','desc')->get();发布于 2018-04-03 10:35:04
然后,您可以尝试如下:
$rows= ProductCategory::withCount('categoryProduct')->get();您可以通过以下方式访问该网站:
foreach ($rows as $row) {
echo $row->categoryProduct_count;
}这是纯粹的雄辩
发布于 2018-04-03 10:28:24
假设您将$categories作为一个集合,那么您可以按函数定义一个自定义排序。
$categories = ProductCategory::all()->with('categoryProduct'); //which will fetch you all categories with products
$sorted = $categories->sortBy(function ($category, $key) {
return count($category);
});https://stackoverflow.com/questions/49627696
复制相似问题