Laravel查询构建器 - 如何按别名分组,或者执行rawByBy [英] Laravel query builder - How to either group by alias, or do raw groupBy

查看:245
本文介绍了Laravel查询构建器 - 如何按别名分组,或者执行rawByBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

对于我的查询的select部分,我可以使用selectRaw,但似乎没有与group by等价。



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



我可以在Illuminate \Database\Query\Grammars\Grammar中找到该方法,其中group by是编译的(compileGroups),我想我可以覆盖它但我不太确定我会怎么做(已阅读Laravel文档)。 解决方案

如果你想你可以做这样的事情......

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


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

解决方案

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

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

这篇关于Laravel查询构建器 - 如何按别名分组,或者执行rawByBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆