简体   繁体   English

Laravel Eloquent:where子句中的函数

[英]Laravel Eloquent: function in where clause

I want my SQL to look like: 我希望我的SQL看起来像:

SELECT ptype, sum(money) FROM `payments` WHERE YEAR(created_at) = 2016 GROUP BY ptype

I am struggling with putting " YEAR(created_at) = 2016 " into Laravel Eloquent query builder... 我正在努力将“ YEAR(created_at)= 2016 ”放入Laravel Eloquent查询构建器中...

Tried different options: 尝试了不同的选择:

$data = \EPA\Models\Payments::where('YEAR(created_at)', '=', intval($period))
->groupBy('ptype')->get();

and with DB::raw: 和DB :: raw:

$data = \EPA\Models\Payments::where(DB::raw('YEAR(created_at)'), '=', intval($period))
->groupBy('ptype')->toSql();

Which gives me error 这给我错误

 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(created_at)'
 in 'where clause' (SQL: select * from `payments` where `YEAR(created_at)` = 2016 group by `ptype`)

or SQL like: 或类似SQL的代码:

select * from `payments` where YEAR(created_at) = ? group by `ptype`

that is also not suitable form me, because third parameter of where clause is replaced with "?" 那也不适合我,因为where子句的第三个参数被替换为“?” suddenly... 突然...

In fact, the issues are that in one case it escapes YEAR(...) and MySQL thinks it is a column, and in second way Eloquent places "?" 实际上,问题在于,在一种情况下,它逃脱了YEAR(...),而MySQL认为这是一列,而在第二种方式中,雄辩的位置是“?”。 instead of year. 而不是年份。

Can somebody help to integrate this where clause with function into eloquent...? 有人可以帮助将具有功能的where子句集成到雄辩的……吗? What is the best way of doing this? 最好的方法是什么? (I need it for my report script) (我的报告脚本需要它)

Like Mark Baker answered in comments, I can use "whereRaw" for the solution: 就像Mark Ba​​ker在评论中回答的一样,我可以使用“ whereRaw”作为解决方案:

$data = \EPA\Models\Payments::selectRaw('ptype, sum( money )')
->whereRaw('YEAR(created_at) = '. intval($period))
->groupBy('ptype')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM