简体   繁体   中英

MySQL YEAR() equivalent in Laravel query builder

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

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

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

$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?

The query builder has a whereYear method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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