Yii2 truncates IP when INET_NTOA

There is an ip property (in the database). Recording is normal. When reading INET_NTOA, Yii truncates the IP to the first point. Displays for example 192, but should When fetching asArray (), everything works fine.
Also, if you create a new property like public $ip_string and select … as ip_string, it displays normally
Where is the bug?

DB ip value = 3232293121 (int(10) unsigned)

$model = Ips::find()->select(['INET_NTOA(ip) ip'])->where(['id' => 89])->one();
echo $model->ip; //return 192

$model = Ips::find()->select(['INET_NTOA(ip) ip_string'])->where(['id' => 89])->one();
echo $model->ip_string; //return (public $ip_string in model)

$model = Ips::find()->select(['INET_NTOA(ip) ip'])->asArray()->where(['id' => 89])->one();
echo $model['ip']; //return

Hi Alexandr,

It’s because ip attribute of Ips model is an integer.

$model = Ips::find()->where(['id' => 89])->;one(); 
echo $model->ip; //return 3232293121 

In the above, Yii will execute a SQL like this:

select * from `ips` where `id` = 89;

And it will return a string of '3232293121' as the ip column value, which will be converted into an integer of 3232293121 when the ActiveRecord model is populated with the query result. It’s natural that a string of '' is converted into an integer of 192.

Note that asArray() preserves the query result as a string, without converting it to the data type of the column. Check the following section of the guide.

Guide > ActiveRecord > Retrieving Data in Arrays

Thank you, I already understood)
I thought there was a way to reassign the property type before/after select/find.


public $ip_string;
public static function find() {
    return parent::find()->select([self::tableName() . '.*, INET_NTOA(' . self::tableName() . '.`ip`) `ip_string`']);

public function getIp() {
    $this->ip = $this->ip_string;

But it`s not work)

The data type of ip is determined as integer implicitly down in the base model of ActiveRecord by referring to the table scheme and I think it’s not a good idea to re-define it as a string. So what we could do would be defining another attribute ip_string as you are doing.

I would leave ip as it is, and would not try to let it return the ip address string.

Thanks for the answer. Just a lot of code will have to be edited) Or leave it in varchar)

Yeah, I agree that redefining ip column as a VARCHAR in the db layer would be a practical and decent solution.