Laravel 查询生成器 - 如何按别名分组,或执行原始 groupBy

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29370577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:16:02  来源:igfitidea点击:

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

mysqllaravelgroup-bylaravel-5query-builder

提问by Geoff Clayton

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:

我的 Laravel 5 应用程序包含一个用于报告运行的动态查询构建器。我需要一些 group by 子句,但遇到了问题。如果我在那里使用实际的 sql,我可能会遇到问题,因为有时在 sql 中需要一个 sql 命令(而不是直接的列名),即 - DAYNAME(table_name.date_column)。Laravel 破坏了这个:

\`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.

对于查询的选择部分,我可以使用 selectRaw,但似乎没有 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.

我想过使用别名(所有选择都是别名),但 Laravel 也将它们包装在“`”字符中。此外 - 我的应用程序需要同时使用 MySQL 和 SQL Server,据我所知,后者不允许在查询的部分分组中使用别名。

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

我可以在 Illuminate\Database\Query\Grammars\Grammar 中找到该方法,其中 group by 被编译(compileGroups),我想我可以覆盖它,但我不太确定我将如何去做(已阅读 Laravel 文档)。

回答by user1669496

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

如果你想做原始的 groupBy,你可以做这样的事情......

...->groupBy(DB::raw('some_alias'))