Yii2 Active Record将zerofill列转换为int丢失零

时间:2015-12-27 13:28:39

标签: php activerecord yii2

我的User表包含zerofill主id

CREATE TABLE `user` (
 `id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB 

我的User模型如下:

class User extends ActiveRecord implements IdentityInterface
{
    public static function tableName()
    {
        return '{{%user}}';
    }
    public static function findIdentity($id)
    {
        $identity = static::findOne(['id' => (int)$id]);

        var_dump($identity); //zeros are lost here
        exit;
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
    public function getId()
    {
        return $this->getPrimaryKey();
    }
    public function getAuthKey()
    {
        return $this->auth_key;
    }
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
}

Active Record会将id投射到int,所以我得到1 00001; 200002,但我想保留零并将id视为string

在x32系统上一切正常,但我们转移到了x64。如何强制Active Record将id视为string

1 个答案:

答案 0 :(得分:0)

Yii从查询结果填充数据中的对象时,会使用方法

\yii\db\ColumnSchema::typecast

从数据库中检索后,Means根据[[phpType]]转换输入值。

如果您的ID是整数,那么将使用下一条规则

    case 'integer':
        return (int) $value;

这就是为什么 00001 转换为 1

的原因

我找到了下一个解决方案,不是最好的,但是无论如何

第一解决方案

每次尝试获取ID时,都会调用下一个函数

    public function getId()
    {
        return str_pad($this->id, 5, '0', STR_PAD_LEFT);
    }

第二个解决方案

覆盖afterFind和afterSave方法


    public function refreshUserId()
    {
        $this->id = str_pad($this->id, 5, '0', STR_PAD_LEFT);
    }

    public function afterFind()
    {
        parent::afterFind();

        $this->refreshUserId();
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        $this->refreshUserId();
    }