Laravel - Eloquent - 返回相关计数大于
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42584706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Eloquent - Return Where Related Count Is Greater Than
提问by Dev.Wol
I have 2 tables.
我有2张桌子。
Products Brands
产品品牌
Im trying to return top 10 brand models with the most products.
我试图用最多的产品返回前 10 名品牌模型。
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
wherebrands
.id
=products
.brand
)
SQLSTATE[42S22]: 列未找到:1054 未知列“brands.id”在“where 子句”中(SQL:从
products
where 中选择 count(*) 作为聚合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');
}
回答by Naco
try this:
尝试这个:
$brands = Brands::has('products', '>' , 10)->with('products')->get();
回答by Samsquanch
You should be able to accomplish this with the withCount
methodif you're using at least Laravel 5.3:
如果您至少使用 Laravel 5.3,您应该能够使用该withCount
方法完成此操作:
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.
你的亲戚products
的名字在哪里。这将在您的查询中为您提供一个新字段products_count
,您可以通过该字段进行订购。