Yousef Altaf
Yousef Altaf

Reputation: 2763

Laravel 5.4 : count the products in each category and sort them by Eloquent query

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

Upvotes: 2

Views: 4868

Answers (3)

afsal c
afsal c

Reputation: 610

Then you can try it as:

$rows= ProductCategory::withCount('categoryProduct')->get();

and you can access this by:

foreach ($rows as $row) {
echo $row->categoryProduct_count;
}

this is pure eloquent

Upvotes: 1

Shobi
Shobi

Reputation: 11451

suppose you get the $categories as a collection then you can define a custom sort by function

    $categories = ProductCategory::all()->with('categoryProduct'); //which will fetch you all categories with products

    $sorted = $categories->sortBy(function ($category, $key) {
        return count($category);
    });

doc link

Upvotes: 0

Sohel0415
Sohel0415

Reputation: 9853

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();

Upvotes: 6

Related Questions