Laravel 查询构建器中的 MySQL YEAR() 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33534677/
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 12:38:29  来源:igfitidea点击:

MySQL YEAR() equivalent in Laravel query builder

phpmysqllaravel

提问by Dadan Hamdani

With MySQL, I can use the YEAR()function like this to filter by the year of a date field in a WHEREclause:

使用 MySQL,我可以使用这样的YEAR()函数来过滤WHERE子句中日期字段的年份:

SELECT noworkorder FROM workorders WHERE YEAR(date)=2015;

In Laravel, I can of course achieve the same thing with a raw expression:

在 Laravel 中,我当然可以使用原始表达式实现相同的目的:

$data = DB::table('workorders')
       ->select('noworkorder')
       ->where(DB::raw('YEAR(date)=2015'))
       ->orderby('noworkorder', 'desc')
       ->get();

But is there a way to do this without raw expressions?

但是有没有办法在没有原始表达式的情况下做到这一点?

回答by Thomas Kim

The query builder has a whereYearmethod:

查询构建器有一个whereYear方法:

$data = DB::table('workorders')
   ->select('noworkorder')
   ->whereYear('date', '=', 2015)
   ->orderby('noworkorder', 'desc')
   ->get();