Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Brand
  • Count

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');
    }
like image 809
Dev.W Avatar asked Mar 03 '17 17:03

Dev.W


2 Answers

try this:

$brands = Brands::has('products', '>' , 10)->with('products')->get();
like image 184
Naco Avatar answered Oct 18 '22 06:10

Naco


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.

like image 38
Samsquanch Avatar answered Oct 18 '22 07:10

Samsquanch