Yii2型铸造列为整数

问题描述 投票:3回答:1

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

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

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

问题是,我得到的结果为“20”。换句话说,20作为字符串返回。如何确保所选的是整数?

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

    Product::find()->select(['id', new Expression('CAST(20 AS UNSIGNED) as type')])
            ->where(['client' => $clientId])
            ->andWhere(['<>', 'hidden', 0]);
php mysql yii yii2
1个回答
6
投票

您可以在ProductafterFind()函数中手动进行类型转换或使用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,
            ],
        ];
    }
© www.soinside.com 2019 - 2024. All rights reserved.