Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel-雄辩-返回相关计数大于_Php_Laravel_Laravel 5_Eloquent - Fatal编程技术网

Php Laravel-雄辩-返回相关计数大于

Php Laravel-雄辩-返回相关计数大于,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我有两张桌子 产品 品牌 我试图用最多的产品返回前十大品牌型号 我试过了 Product::select('brand', DB::raw('count(brand) as count'))->groupBy('brand')->orderBy('count','desc')->take(10)->get(); 但这不会返回孔模型,只返回 烙印 计数 我也试过了 return $brands = Brand::whereHas('products', functi

我有两张桌子

产品 品牌

我试图用最多的产品返回前十大品牌型号

我试过了

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:选择count(*)作为
products
其中
品牌
标识=
产品
品牌

我的品牌型号

public function products()
    {
        return $this->hasMany('App\Product','brand');
    }
public function manuf()
    {
        return $this->belongsTo('App\Brand','brand');
    }
我的产品型号

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

如果您至少使用了Laravel 5.3,您应该能够通过以下方式完成此任务:

Brand::withCount('products')->orderBy('products_count', 'DESC')->take(10)->get();
其中,
products
是您关系的名称。这将在查询中为您提供一个新字段,
products\u count
,您可以通过该字段进行订购。

尝试以下操作:

$brands = Brands::has('products', '>' , 10)->with('products')->get();

请展示您的关系:)@Khanshahrukh您的品牌表名为
品牌
品牌
?可能是您需要明确地告诉laravel您的表名是什么,以阻止其多元化。我的表名为Brands。这将只显示产品型号,而我只关注品牌型号。这将转换为SQL as
SELECT*,COUNT('Brand')作为产品组中的计数按品牌顺序按计数描述限制10。从你的问题来看,这似乎正是你想要的。如果不是这样,请澄清问题。在我的问题中,我通过问“我正在尝试返回产品最多的前十大品牌型号”来澄清。为误解道歉。更新答案。请注意,它只能在5.3或更高版本上工作。感谢您的解决方案,这对我在Laravel 5.4中的工作非常有用:)