Laravel
从 5.4
版本开始, 默认使用 utf8mb4
. 如果执行 php artisan migrate
命令报 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long;
之类的语法错误, 就需要做些特殊处理.
# php artisan migrate --seed
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
In Connection.php line 664:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
In Connection.php line 458:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes
解决方案
限制
migrate
生成的默认字符串长度为191
: 在App\Providers\AppServiceProvider
的boot()
方法里添加配置:use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
修改
app/config/database.php
对应数据库配置:'charset' => 'utf8mb4', // 改成 utf8 'collation' => 'utf8mb4_unicode_ci', // 改成 utf8_unicode_ci
- 升级
MySQL
版本到5.5.3
以上
原因
Laravel
从 5.4
版本开始, 默认使用 utf8mb4
编码.
MySQL
支持的 utf8
编码最大字符长度为 3
字节,如果遇到 4
字节的宽字符就会出现插入异常.
默认情况下 MySQL
InnoDB
引擎单一字段索引的长度是 767
字节, 如编码是 utf8mb4
最大可能占 4
个字节(767/4 约等于 191), 如果超出 191
就报错了.
你这边的主题很nice啊。
😀 你的主题也不错