在 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]);
最佳答案
您可以在Product
的afterFind()
中手动进行类型转换功能或使用 AttributeTypecastBehavior
.
但最重要的是,您必须为您在查询中使用的别名定义一个自定义属性
。例如,如果您使用 selling_price
作为别名,则 Product
模型中的 $selling_price
。
public $selling_price;
之后,您可以使用以下任何一种方法。
1) afterFind
下面的例子
public function afterFind() {
parent::afterFind();
$this->selling_price = (int) $this->selling_price;
}
下面的例子
public function behaviors()
{
return [
'typecast' => [
'class' => \yii\behaviors\AttributeTypecastBehavior::className(),
'attributeTypes' => [
'selling_price' => \yii\behaviors\AttributeTypecastBehavior::TYPE_INTEGER,
],
'typecastAfterValidate' => false,
'typecastBeforeSave' => false,
'typecastAfterFind' => true,
],
];
}
关于php - Yii2 将列类型转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48622467/