我有两张桌子。
产品品牌
我试着用最多的产品回归十大品牌车型。
我试过了。
Product::select('brand', DB::raw('count(brand) as count'))->groupBy('brand')->orderBy('count','desc')->take(10)->get();但这不会返回洞模型,而只返回
我也试过
return $brands = Brand::whereHas('products', function($q) {
$q->count() > 10;
})->get();但我知道错误是:
SQLSTATE42S22:未找到列:'where子句‘中1054个未知列'brands.id’(SQL:从
productswherebrands.id=products.brand中选择count(*)作为聚合项)
我的品牌模型
public function products()
{
return $this->hasMany('App\Product','brand');
}我的产品模型
public function manuf()
{
return $this->belongsTo('App\Brand','brand');
}发布于 2017-03-03 17:25:44
如果您使用的是Laravel5.3,那么您应该能够用 method完成这一任务:
Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();其中products是您关系的名称。这将在查询中为您提供一个新字段,products_count,您可以根据该字段进行订购。
https://stackoverflow.com/questions/42584706
复制相似问题