Yii2 将列类型转换为整数

Yii2 type cast column as integer

在Yii2中,我有一个模型,例如Product。我想要做的是 select 数据库中的一个额外列作为 int

这是我正在做的一个例子:

Product::find()->select(['id', new Expression('20 as type')])
            ->where(['client' => $clientId])
            ->andWhere(['<>', 'hidden', 0]);

问题是,我得到的结果是“20”。换句话说,20 作为字符串返回。我怎样才能确保 selected 是整数?

我也尝试了以下但它不起作用:

    Product::find()->select(['id', new Expression('CAST(20 AS UNSIGNED) as type')])
            ->where(['client' => $clientId])
            ->andWhere(['<>', 'hidden', 0]);

您可以在 ProductafterFind() function or use AttributeTypecastBehavior 中手动进行类型转换。

但最重要的是,您必须为查询中使用的别名定义自定义 attribute。例如,如果您使用 selling _price 作为别名,则 Product 模型中的 $selling_price

public $selling_price;

之后,您可以使用以下任何一种方法。

1) afterFind

下面的例子

public function afterFind() {
    parent::afterFind();
    $this->selling_price = (int) $this->selling_price;
}

2) AttributeTypecastBehavior

下面的例子

 public function behaviors()
    {
        return [
            'typecast' => [
                'class' => \yii\behaviors\AttributeTypecastBehavior::className(),
                'attributeTypes' => [
                    'selling_price' => \yii\behaviors\AttributeTypecastBehavior::TYPE_INTEGER,

                ],
                'typecastAfterValidate' => false,
                'typecastBeforeSave' => false,
                'typecastAfterFind' => true,
            ],
        ];
    }