Friday, March 3, 2017

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');
    }



via Dev.Wol

Advertisement