1366 Yii 2 用户表迁移期间出现不正确的字符串值错误


1366 Incorrect string value Error During Yii 2 User Table Migration

我正在使用迁移脚本使用 Yii 2 的迁移来创建和插入数据库值当我迁移时,它向我显示此错误:

*** applying m141125_045122_create_user_table
    > create table {{%user}} ... done (time: 0.009s)
    > insert into {{%user}} ...Exception 'yii'db'Exception' with message 'SQLSTA
TE[HY000]: General error: 1366 Incorrect string value: ''x9A'xD6M'xAE'x02g...' f
or column 'auth_key' at row 1
The SQL being executed was: INSERT INTO `user` (`username`, `password_hash`, `au
th_key`, `email`, `created_at`, `updated_at`) VALUES ('admin', '$2y$13$zKGigop9G
zmAkrfa8FSJIuebOOnNGDMsNuePwniQW60H7vnubaOwC', 'Ü╓M«☻gHt■Sα◄?↕ºo?Xèö▐ É¬=1N↑αï╨+
', 'admin@example.com', NOW(), NOW())'
in C:'Apache24'htdocs'media_avenue'vendor'yiisoft'yii2'db'Schema.php:532
Error Info:
Array
(
    [0] => HY000
    [1] => 1366
    [2] => Incorrect string value: ''x9A'xD6M'xAE'x02g...' for column 'auth_key'
 at row 1
)

这是我的迁移脚本:

public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8mb4  COLLATE utf8mb4_unicode_ci ENGINE=InnoDB';
        }
        $this->createTable('{{%user}}', [
            'id' => Schema::TYPE_PK,
            'username' => Schema::TYPE_STRING . ' NOT NULL',
            'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
            'password_hash' => Schema::TYPE_STRING . ' NOT NULL',
            'password_reset_token' => Schema::TYPE_STRING,
            'email' => Schema::TYPE_STRING . ' NOT NULL',
            'role' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
            'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
            'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ], $tableOptions);
        $this->insert('{{%user}}', [
            'username' => 'admin',
            'password_hash' => Yii::$app->security->generatePasswordHash('admin'),
            'auth_key' => Yii::$app->security->generateRandomKey(),
            'email'=> Yii::$app->params['adminEmail'],
            'created_at'=> new Expression('NOW()'),
            'updated_at'=> new Expression('NOW()'),
        ]);
    }

我的MySQL版本是5.6.21.1,我尝试通过将编码从utf8更改为utf8mb4来弄乱编码,但它仍然不起作用

这是什么原因呢?

注意:

  • 如果我使用 XAMPP,我不会收到此错误。

  • 仅当我手动安装MySQL时才会显示错误

使用 generateRandomString() 而不是 generateRandomKey()

由于函数的实现在 Yii 2 中发生了变化。

https://github.com/yiisoft/yii2/blob/master/framework/base/Security.php#L462https://github.com/yiisoft/yii/blob/1.1.15/framework/base/CSecurityManager.php#L86