本文介绍了如何使用 Yii 2 构建像 `select ... where id % 2 = 1` 这样的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当然,我可以Yii::$app->db->createCommand($sql)->query(),但是如果我想使用 ActiveRecord::find()->where($conditions) 来完成这项工作怎么办?

Surely, I can Yii::$app->db->createCommand($sql)->query(),but what if I wanna use a ActiveRecord::find()->where($conditions) to do this job ?

推荐答案

这是使用 yiidbExpression 的选项之一:

Here is one of the options with using yiidbExpression:

use yiidbExpression;

...

$models = Customer::find()
    ->select(['id', 'name', ...])
    ->where(new Expression('id % 2 = 1')])
    ->all();

它绝对比原始 sql 和 ['%2=', 'id', 1] 更好,因为它遵循顺序并且在我看来更具可读性.

It's definetely better than raw sql and ['%2=', 'id', 1] because it follows the order and more readable in my opinion.

['%2=', 'id', 1] 也不适合这里,因为 %2= 实际上不是像 那样的运算符不在like 例如,所以运算符、值和 = 符号是混合在一起的.

['%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,他是官方 Gitter 聊天中的主要框架贡献者之一,他说正确的做法是使用 yiidbExpression.

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 yiidbExpression.

这篇关于如何使用 Yii 2 构建像 `select ... where id % 2 = 1` 这样的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:42