在Yii2中,我有一个模型,例如Product
。我想要做的是从数据库中选择一个额外的列作为int
这是我正在做的事情的一个例子:
Product::find()->select(['id', new Expression('20 as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
问题是,我得到了结果&#34; 20&#34;。换句话说,20作为字符串返回。如何确保所选的是整数?
我也尝试了以下内容,但它不起作用:
Product::find()->select(['id', new Expression('CAST(20 AS UNSIGNED) as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
答案 0 :(得分:6)
您可以在Product
的{{3}}功能中手动进行类型转换,也可以使用SE.RE。
但最重要的是,您必须为查询中使用的别名定义自定义attribute
。例如,如果您使用$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,
],
];
}