代码之家  ›  专栏  ›  技术社区  ›  mrateb

Yii2类型强制转换为整数的列

  •  6
  • mrateb  · 技术社区  · 8 年前

    例如,在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]);
    
    1 回复  |  直到 8 年前
        1
  •  12
  •   rob006    8 年前

    您可以手动输入 Product afterFind() 功能或用途 AttributeTypecastBehavior .

    但最重要的是,您必须定义一个自定义 attribute 用于查询中使用的别名。例如 $selling_price 在您的 产品 型号(如果使用) 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,
                ],
            ];
        }