Laravel-雄辩-返回相关计数大于 [英] Laravel - Eloquent - Return Where Related Count Is Greater Than

查看:83
本文介绍了Laravel-雄辩-返回相关计数大于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2张桌子.

产品 品牌

我正在尝试用最多的产品返回十大品牌型号.

Im trying to return top 10 brand models with the most products.

我已经尝试过了.

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

  • 品牌

我也尝试过

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

但是我得到了错误:

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

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)

我的品牌模型

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-雄辩-返回相关计数大于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆