jrean's avatar

Query where created_at ...

Hi,

I would like to query a model where the year of the timestamp created_at is equal to the current year or a given year.

I'm using SQLITE

I found while googling the following solution:

->whereRaw("strftime('%Y', created_at) = strftime('%Y', date('now'))")->get();
  • Is there a better solution? Something more elegant? (I'm not an expert at all)

This query produces the following:

select * from "xxx" where "xxx_id" = ? and strftime('%Y', created_at) = strftime('%Y', date('now'))

Curious, I also tried with:

->where( \DB::raw("strftime('%Y', created_at) = strftime('%Y', date('now'))") )->get();

It returns an empty array and the query produces the following:

select * from "xxx" where "xxx" = ? and strftime('%Y', created_at) = strftime('%Y', date('now')) is null

Any help is welcome :)

0 likes
2 replies
constb's avatar
constb
Best Answer
Level 6

@jrean

->whereBetween('created_at', [ Carbon::now()->startOfYear(), Carbon::now()->endOfYear() ]);
4 likes

Please or to participate in this conversation.