0
votes

In SQL I could able to select records that their ids dividable by 4:

SELECT id FROM table_name WHERE id%4 = 0;

I tried to do that in Yii2 active record but it failed with error:

$model = Verses::find()->where(['%4','id',0])->orderBy('id')->all();

Is there any way or documentation hint about this?

3
have you tried $model = Verses::find()->where(['=','id%4',0])->orderBy('id')->all(); - Serghei Leonenco
Do you want the solution with ActiveRecord only? - Basheer Kharoti
Also you can try to use having() to filter results, Something like this: $model = Verses::find()->orderBy('id')->groupBy('id')->having([['id % 4' => 0]])->all(); - Serghei Leonenco
@SergheiLeonenco I just have tried ['=','id%4',0] but with error too. - SaidbakR
Can you post you error code - Serghei Leonenco

3 Answers

1
votes

Also you can do it this way:

$model = Verses::find()->where(['(id % 4)' => 0])->orderBy('id')->all();

The error was showing that Unknown column 'id%4' In order to express this as a math expression we enclose this in the brackets an add this in to the query.

0
votes

The safest way is to use Expression:

$model = Verses::find()->where(new Expression('id%4 = 0'))->orderBy('id')->all();

While adding parentheses in ->where(['(id % 4)' => 0]) may work, it is pretty hacky it this behavior was nearly removed in recent version of Yii, so I would not rely on it that much.

-1
votes

I have found the solution by try and error:

$model = Verses::find()->where(['%4=','id',0])->orderBy('id')->all();

In other words, the = sign should be concatenated to the modulus operation i.e %4=.