In Yii2, I have a model, for example Product
. What I want to do is select an extra column from the database as int
This is an example of what I'm doing:
Product::find()->select(['id', new Expression('20 as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
The problem is, I'm getting the result as "20". In other words, 20 is returned as string. How can I make sure that the selected is Integer?
I tried the following also but its not working:
Product::find()->select(['id', new Expression('CAST(20 AS UNSIGNED) as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
You can manually typecast in Product
's afterFind()
function or use AttributeTypecastBehavior
.
But above all, you'll have to define a custom attribute
for alias you use in the query. For example $selling_price
in your Product
model if you use selling _price
as an alias.
public $selling_price;
After that, you can use any of the following approaches.
1) afterFind
Example Below
public function afterFind() {
parent::afterFind();
$this->selling_price = (int) $this->selling_price;
}
2) AttributeTypecastBehavior
Example below
public function behaviors()
{
return [
'typecast' => [
'class' => \yii\behaviors\AttributeTypecastBehavior::className(),
'attributeTypes' => [
'selling_price' => \yii\behaviors\AttributeTypecastBehavior::TYPE_INTEGER,
],
'typecastAfterValidate' => false,
'typecastBeforeSave' => false,
'typecastAfterFind' => true,
],
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With