Dev.W
Dev.W

Reputation: 2370

Laravel - Eloquent - Return Where Related Count Is Greater Than

I have 2 tables.

Products Brands

Im trying to return top 10 brand models with the most products.

I've tried.

Product::select('brand', DB::raw('count(brand) as count'))->groupBy('brand')->orderBy('count','desc')->take(10)->get();

But that doesn't return the hole model and only returns

I've also tried

 return $brands = Brand::whereHas('products', function($q) {
           $q->count() > 10;
       })->get();

But I get the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'brands.id' in 'where clause' (SQL: select count(*) as aggregate from products where brands.id = products.brand)

My Brand Model

public function products()
    {
        return $this->hasMany('App\Product','brand');
    }

My Product Model

public function manuf()
    {
        return $this->belongsTo('App\Brand','brand');
    }

Upvotes: 18

Views: 26554

Answers (2)

Naco
Naco

Reputation: 862

try this:

$brands = Brands::has('products', '>' , 10)->with('products')->get();

Upvotes: 41

Samsquanch
Samsquanch

Reputation: 9146

You should be able to accomplish this with the withCount method if you're using at least Laravel 5.3:

Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();

Where products is the name of your relation. This will give you a new field in your query, products_count that you can order by.

Upvotes: 6

Related Questions