Yii2 DataFilter 构建错误条件

Yii2 DataFilter builds wrong condition

我必须在请求中按日期进行过滤。我知道现有的 yii\data\DataFilter class,所以我用它来解决问题。

实际请求URL(示例):https://api.site.com/module/post?filter[from_date][>=]=100 不用担心值 100,我们在我们的策略中使用 UNIX。

我使用yii\rest\ActiveController来执行动作,所以我在[[actions()]]:

中定义了dataFilter属性
public function actions()
{
    $actions = parent::actions();
    $actions['index']['dataFilter'] = [
        'class' => DataFilter::class,
        'attributeMap' => [
            'from_date' => 'date_success',
            'to_date' => 'date_success',
        ],
        'searchModel' => function () {
            return (new DynamicModel(['from_date', 'to_date']))
                ->addRule(['from_date', 'to_date'], 'integer', ['min' => 0]);
        },
    ];
    return $actions;
}

查询完成后,返回一个空数组[]。我跟踪了 SQL 个查询:

如您所见,有 "EQUALS" 操作数而不是“>”,它在查询字符串 ?filter[from_date][>]=100.

中定义

默认在yii\rest\IndexAction变量$query中调用方法where($filter):

/*
After successful filter build $filter variable becomes:
    $filter = [
        'date_success' => [
            '>' => 100,
        ],
    ]
*/

$query = $modelClass::find();
if (!empty($filter)) {
    $query->andWhere($filter);
}

为什么会这样?我调试了代码,发现了一个有趣的特性!在 yii\db\conditions\HashConditionBuilder:

public function build(ExpressionInterface $expression, array &$params = [])
{
    $hash = $expression->getHash();
    $parts = [];
    foreach ($hash as $column => $value) {
        if (ArrayHelper::isTraversable($value) || $value instanceof Query) {
            // IN condition
            // Executing will be here.
            // Yii2 thinks thats 'IN' condition, and builds as 'IN'.
            $parts[] = $this->queryBuilder->buildCondition(new InCondition($column, 'IN', $value), $params);
        } else {
            if (strpos($column, '(') === false) {
                $column = $this->queryBuilder->db->quoteColumnName($column);
            }
            if ($value === null) {
                $parts[] = "$column IS NULL";
            } elseif ($value instanceof ExpressionInterface) {
                $parts[] = "$column=" . $this->queryBuilder->buildExpression($value, $params);
            } else {
                $phName = $this->queryBuilder->bindParam($value, $params);
                $parts[] = "$column=$phName";
            }
        }
    }
    return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
}

这个问题在不同的 'conditionOperators' 上重复出现,结果完全相同。

filter[from_date][=]=100
filter[from_date][<]=100
filter[from_date][gt]=100
filter[from_date][gte]=100

ActiveDataFilterDataFilter 之间存在一处粘性差异。它在方法 [[buildInternal()]].

中得出结论

DataFilter方法:

protected function buildInternal()
{
    return $this->normalize(false);
}

ActiveDataFilter方法:

protected function buildInternal()
{
    $filter = $this->normalize(false);
    if (empty($filter)) {
        return [];
    }
    return $this->buildCondition($filter);
}

通过调用 $this->buildCondition($filter) ActiveDataFilter 传递 $filter 变量然后应用 QueryBilders,因此 $filter 变量变为:

$filter = ['>', 'date_success', 100];