Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query builder - How to either group by alias, or do raw groupBy

My Laravel 5 app includes a dynamic query builder for report running. I need some group by clauses in there and have run into a problem. If I use actual sql in there I can have issues as sometimes there needs to be a sql command in amongst the sql (as opposed to straightforward column names), ie - DAYNAME(table_name.date_column). Laravel mangles this:

\`DAYNAME(table_name\`.\`date_column)\`

For the select part of my query I can use selectRaw, but there does not seem to be an equivaent for group by.

I thought of using aliases (all the selects are aliased) but Laravel wraps them in "`" characters as well. Besides - my app needs to work with both MySQL and SQL Server and as far as I know the latter does not allow aliases in the group by section of the query.

I can find the method in Illuminate\Database\Query\Grammars\Grammar where the group by is compiled (compileGroups) and I suppose I could override it but I'm not too sure how I would go about that (have read the Laravel docs).

like image 461
Geoff Clayton Avatar asked Mar 31 '15 14:03

Geoff Clayton


1 Answers

If you want to do raw groupBy, you can do something like this...

...->groupBy(DB::raw('some_alias'))
like image 98
user1669496 Avatar answered Oct 07 '22 17:10

user1669496