Yii2 Active Record 其中 % 模数
Yii2 Active Record where % modulus
在 SQL 中我可以 select 记录他们的 ID 可被 4 整除:
SELECT id FROM table_name WHERE id%4 = 0;
我尝试在 Yii2 活动记录中这样做,但失败并出现错误:
$model = Verses::find()->where(['%4','id',0])->orderBy('id')->all();
有什么方法或文档提示吗?
我通过试错找到了解决方案:
$model = Verses::find()->where(['%4=','id',0])->orderBy('id')->all();
换句话说,=
符号应该连接到模运算,即 %4=
。
你也可以这样做:
$model = Verses::find()->where(['(id % 4)' => 0])->orderBy('id')->all();
错误显示 Unknown column 'id%4'
为了将其表示为数学表达式,我们将其括在方括号中并将其添加到查询中。
最安全的方法是使用Expression
:
$model = Verses::find()->where(new Expression('id%4 = 0'))->orderBy('id')->all();
虽然在 ->where(['(id % 4)' => 0])
中添加圆括号可能有效,但在 Yii 的最新版本中几乎删除了这种行为,所以我不会太依赖它。
在 SQL 中我可以 select 记录他们的 ID 可被 4 整除:
SELECT id FROM table_name WHERE id%4 = 0;
我尝试在 Yii2 活动记录中这样做,但失败并出现错误:
$model = Verses::find()->where(['%4','id',0])->orderBy('id')->all();
有什么方法或文档提示吗?
我通过试错找到了解决方案:
$model = Verses::find()->where(['%4=','id',0])->orderBy('id')->all();
换句话说,=
符号应该连接到模运算,即 %4=
。
你也可以这样做:
$model = Verses::find()->where(['(id % 4)' => 0])->orderBy('id')->all();
错误显示 Unknown column 'id%4'
为了将其表示为数学表达式,我们将其括在方括号中并将其添加到查询中。
最安全的方法是使用Expression
:
$model = Verses::find()->where(new Expression('id%4 = 0'))->orderBy('id')->all();
虽然在 ->where(['(id % 4)' => 0])
中添加圆括号可能有效,但在 Yii 的最新版本中几乎删除了这种行为,所以我不会太依赖它。