[英]Laravel - Eloquent - Return Where Related Count Is Greater Than
我有2張桌子。
產品品牌
我試圖用最多的產品回歸十大品牌。
我試過了。
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();
但我得到錯誤:
列未找到:SQLSTATE [42S22] 1054未知列'brands.id'在'where子句'(SQL:SELECT COUNT(*)從總
products
,其中brands
。id
=products
。brand
)
我的品牌模特
public function products()
{
return $this->hasMany('App\Product','brand');
}
我的產品型號
public function manuf()
{
return $this->belongsTo('App\Brand','brand');
}
試試這個:
$brands = Brands::has('products', '>' , 10)->with('products')->get();
如果您至少使用Laravel 5.3,您應該可以使用withCount
方法完成此操作:
Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();
products
是您的關系的名稱。 這將在您的查詢中為您提供一個新字段,您可以訂購products_count
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.