Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3 QueryBuilder: condition for few values does not generate 'IN' statement

In CakePHP 2 when you write something like that:

$Model->find('all', ['conditions' => ['field' => 1]]);

You will get query which looks like this:

SELECT * FROM model WHERE model.field = 1;

Or when you write something like that:

$Model->find('all', ['conditions' => ['field' => [1,2,3,5]]]);

You will get query which like this:

SELECT * FROM model WHERE model.field IN (1,2,3,5);

What I mean, is that the 'IN' statement is generated automatically depending on the type of argument.

On the other hand in CakePHP 3 when you write

$Table->find()->where(['field' => [1,2,3]])->all();

you will receive an error, e.g.

Cannot convert value to integer

because it generates statement like this:

SELECT * FROM table WHERE table.field = Array();

Is this a bug or a feature?

like image 871
sikor Avatar asked Dec 04 '15 09:12

sikor


1 Answers

According to the official docs you need to indicate the column data type in CakePHP 3:-

$Table->find()->where(['field' => [1,2,3], ['field' => 'integer[]']])->all();

integer[] is telling Cake to expect an array of integers.

Alternatively you can include IN in your condition:-

$Table->find()->where(['field IN' => [1,2,3]])->all();

Both cases will cast the data to an array if it's not already so that the IN will work as expected if only an integer value is passed.

like image 106
drmonkeyninja Avatar answered Oct 04 '22 22:10

drmonkeyninja