简体   繁体   English

在 laravel 5 中按子实体分组,并带有 eloquent

[英]group by child entity in laravel 5 with eloquent

I have this tables (simplified):我有这个表(简化):

products:
    id,
    model_id,
    color

models:
   id,
   name

And I want to know how many products do i have of each model and each color, in sql I can do it this way:我想知道每种型号和每种颜色有多少产品,在 sql 中我可以这样做:

SELECT models.name, count(*) 
FROM models
INNER JOIN products ON (models.id = products.model_id)
group by products.color, products.model_id

But I can't doit with eloquent, this is my code:但我不能用 eloquent,这是我的代码:

Model::with('products','products.model')->groupBy('products.color')->groupBy('products.model')->get();

throws this error:抛出这个错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.color' in 'group statement' 

It's like eloquent does not knows the relationship model with products, what i'm missing?就像 eloquent 不知道与产品的关系模型,我缺少什么?

Update: Moein sends me in the rigth direction, i can solve it by doing this:更新:Moein 向我发送了正确的方向,我可以通过这样做来解决它:

Model::join('products', 'models.id', '=', 'products.model_id')
                ->selectRaw('products.*, count(*)')
                ->groupBy('products.color')
                ->groupBy('products.modelo_id')
                -> get();

Update: Moein sends me in the rigth direction, i can solve it by doing this:更新:Moein 向我发送了正确的方向,我可以通过这样做来解决它:

Model::join('products', 'models.id', '=', 'products.model_id')
            ->selectRaw('products.*, count(*)')
            ->groupBy('products.color')
            ->groupBy('products.modelo_id')
            -> get();

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

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