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

1

16

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).

Rori answered 31/3, 2015 at 14:7 Comment(0)
S
42

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

...->groupBy(DB::raw('some_alias'))
Superheterodyne answered 31/3, 2015 at 14:10 Comment(4)
This answer helped me until I ran into this problem: https://mcmap.net/q/747859/-in-laravel-how-to-groupby-url-without-parameter-in-the-query/470749Rhpositive
That seems to be a different issue and doesn't add any context to this question.Superheterodyne
I couldn't do GROUP BY column DESC ... this answer saved me, Thanks!Symphonist
@Symphonist You can do ORDER By column DESCEquable

© 2022 - 2024 — McMap. All rights reserved.