【问题标题】:Yii2 Active Record casts zerofill column to int losing zerosYii2 Active Record 将 zerofill 列转换为 int 丢失零
【发布时间】:2015-12-27 13:28:38
【问题描述】:

我有 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 for 00001; 2 用于00002 等,但我想保留零并将id 视为string

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

【问题讨论】:

    标签: php activerecord yii2


    【解决方案1】:

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

    \yii\db\ColumnSchema::typecast
    

    表示从数据库中检索后根据[[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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2013-06-17
      • 2014-03-05
      • 1970-01-01
      相关资源
      最近更新 更多