简体   繁体   中英

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:

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:

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?

Update: Moein sends me in the rigth direction, i can solve it by doing this:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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