Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 type cast column as integer

Tags:

php

mysql

yii

yii2

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]);
like image 958
mrateb Avatar asked Feb 05 '18 12:02

mrateb


1 Answers

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,
            ],
        ];
    }
like image 112
Irfan Ashraf Avatar answered Nov 17 '22 18:11

Irfan Ashraf