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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:27:50  来源:igfitidea点击:

Laravel - Eloquent - Return Where Related Count Is Greater Than

phplaravellaravel-5eloquent

提问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 productswhere brands.id= products.brand)

SQLSTATE[42S22]: 列未找到:1054 未知列“brands.id”在“where 子句”中(SQL:从productswhere 中选择 count(*) 作为聚合brandsid= 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 withCountmethodif you're using at least Laravel 5.3:

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

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

Where productsis the name of your relation. This will give you a new field in your query, products_countthat you can order by.

你的亲戚products的名字在哪里。这将在您的查询中为您提供一个新字段products_count,您可以通过该字段进行订购。