简体   繁体   English

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

[英]Laravel - Eloquent - Return Where Related Count Is Greater Than

I have 2 tables. 我有2张桌子。

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 但这不会返回洞模型而只会返回

  • 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 where brands . id = products . brand ) 列未找到:SQLSTATE [42S22] 1054未知列'brands.id'在'where子句'(SQL:SELECT COUNT(*)从总products ,其中brandsid = productsbrand

My Brand Model 我的品牌模特

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

My Product Model 我的产品型号

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

试试这个:

$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: 如果您至少使用Laravel 5.3,您应该可以使用withCount方法完成此操作:

Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();

Where products is the name of your relation. products是您的关系的名称。 This will give you a new field in your query, products_count that you can order by. 这将在您的查询中为您提供一个新字段,您可以订购products_count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM