Reputation: 1743
SELECT COUNT(*) as count, MONTH(begin_date) FROM `events` WHERE (YEAR(begin_date) = YEAR(CURDATE())) OR (YEAR(begin_date) = YEAR(CURDATE()) + 1) GROUP BY MONTH(begin_date)
Here is sql query, i want to write it in laravel eloquent.
what i try:
$oncoming_events = DB::table('events') ->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)')) ->where('YEAR(begin_date)', '=', 'YEAR(CURDATE())') ->orWhere('YEAR(begin_date)', '=', 'YEAR(CURDATE()) +1') ->groupBy('MONTH(begin_date)')->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(begin_date)' in 'where clause' (SQL: select count(*) as numOfOncomingEvents, MONTH(begin_date) from
events
whereYEAR(begin_date)
=
laravel 5.6
btw sql query works..
Upvotes: 1
Views: 1766
Reputation: 132
You need to use DB::raw()
in where to tell the query builder that it is not column name it is data manipulation in query,
$oncoming_events = DB::table('events')->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))->where(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE())')->orWhere(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE()) +1')->groupBy(DB::raw('MONTH(begin_date)'))->get();
Upvotes: 2