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
wherebrands
.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');
}
try this:
$brands = Brands::has('products', '>' , 10)->with('products')->get();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With