Question

Global context

I'm using a the Laravel's query builder and a SQLite database. Of course datetime type doesn't exist with SQLite and I use strftime to convert my timestamp to month or year value.

The subtleties with SQlite I just discover

The following query works (tested directly with the SQLite Manager):

SELECT * FROM "articles" 
WHERE strftime("%Y", mydate, "unixepoch", "localtime") = "2013"

This one doesn't work:

SELECT * FROM "articles" 
WHERE strftime("%Y", mydate, "unixepoch", "localtime") = 2013

As far as I understand the comparison must be done with strings.

The problem

How to resolve it with Laravel's query builder?

I've read that for DB's specific function I have to use DB::raw tool.

$articles = DB::table('articles')
->where(DB::raw('strftime("%Y", articles.date,  "unixepoch", "localtime") '), $annee)
->orderBy('date', 'DESC')->toSql();

But the problem is the parameter $annee which is interpreted like a number when building the query.

I know there is no cast in PHP, and the interpretation depends of the context. Is there a way to influence the interpretation?

Was it helpful?

Solution 2

Type casting is supported in PHP, but only to string, array, float, int and object.

DB::table('articles')
->where( 'myColumn', (string) $annee)
->orderBy('date', 'DESC')->toSql();

But a quick and dirty way to do it is simply add a string to it.

DB::table('articles')
->where('myColumn', "" + $annee)
->orderBy('date', 'DESC')->toSql();

OTHER TIPS

Type casting is absolutely supported in PHP.

But a quick and dirty way to do it is simply add a string to it.

$articles = DB::table('articles')
->where(DB::raw('strftime("%Y", articles.date,  "unixepoch", "localtime") '), "" + $annee)
->orderBy('date', 'DESC')->toSql();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top