Laravel - Eloquent - 相关数量大于的回报

Dev*_*Wol 5 php laravel eloquent laravel-5

我有2张桌子.

产品品牌

我试图用最多的产品回归十大品牌.

我试过了.

Product::select('brand', DB::raw('count(brand) as count'))->groupBy('brand')->orderBy('count','desc')->take(10)->get();
Run Code Online (Sandbox Code Playgroud)

但这不会返回洞模型而只会返回

  • 计数

我也试过了

 return $brands = Brand::whereHas('products', function($q) {
           $q->count() > 10;
       })->get();
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'brands.id'(SQL:从products 其中选择count(*)作为聚合brands.id= products.brand)

我的品牌模特

public function products()
    {
        return $this->hasMany('App\Product','brand');
    }
Run Code Online (Sandbox Code Playgroud)

我的产品型号

public function manuf()
    {
        return $this->belongsTo('App\Brand','brand');
    }
Run Code Online (Sandbox Code Playgroud)

Nac*_*aco 13

试试这个:

$brands = Brands::has('products', '>' , 10)->with('products')->get();
Run Code Online (Sandbox Code Playgroud)

  • 知道 10 是否是品牌表列的值吗? (2认同)

Sam*_*nch 6

如果您至少使用 Laravel 5.3,您应该能够使用以下方法完成此操作withCount

Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();
Run Code Online (Sandbox Code Playgroud)

products你的亲戚的名字在哪里。这将为您的查询提供一个新字段,products_count您可以根据该字段进行排序。