问题描述
当然,我能的Yii :: $ APP-> DB-> createCommand($ SQL) - >查询()
,但如果我想用什么的ActiveRecord ::找到() - >?在哪里($条件)
来做好这项工作。
Surely, I can Yii::$app->db->createCommand($sql)->query()
,but what if I wanna use a ActiveRecord::find()->where($conditions)
to do this job ?
推荐答案
下面是选项,使用警予\ DB \防爆pression
之一:
Here is one of the options with using yii\db\Expression
:
use yii\db\Expression;
...
$models = Customer::find()
->select(['id', 'name', ...])
->where(new Expression('id % 2 = 1')])
->all();
这是definetely比原始的SQL更好, ['%2 =','身份证',1]
,因为它遵循的顺序,在我看来更具有可读性。
It's definetely better than raw sql and ['%2=', 'id', 1]
because it follows the order and more readable in my opinion.
['%2 =','身份证',1]
也不太适合这里,因为%2 =
其实不是像操作员不在
或喜欢
例如,因此运营商,价值和 = 符号混合在一起。
['%2=', 'id', 1]
also is not suitable here because %2=
is not actually an operator like not in
or like
for example, so operator, value and =
sign are kind of mixed together.
官方文档:
更新:我问 samdark ,官方小胶质主体框架的贡献者之一聊天,他说,正确的做法是用警予\ DB \防爆pression
。
Update: I asked samdark, one of the main framework contributors in official Gitter chat and he said that the right way to do it is using yii\db\Expression
.
这篇关于如何建立类似的查询'选择...其中id%2 = 1`使用Yii 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!