Column not found: 1054 Unknown column 'sum(rating)'


#1

When I use this code
CarRating::select('sum(rating) as total')->get();

I get SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘sum(rating)’ in ‘field list’

But when I use
CarRating::select('rating as total')->get();
or
CarRating::select("rating")->sum('rating');

it works well.

I don’t understand why I am getting an error in the first query.


#2

Which db library is this?


#3

Mysql behind Slim 3 Eloquent


#4

Eloquent’s select() method expects you to give it a list of column names. You are also allowed to alias them, as you discovered in the second (and working) example. But you can’t give it a function. You might want to look at Eloquent’s selectRaw method instead.


#5

Thanks, you are right.

I would have use

CarRating::selectRaw('rating as total')->get();

instead of

CarRating::select('rating as total')->get();