錯誤
運行php artisan migrate出現(xiàn)如下錯誤:
In Connection.php line 664:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table
`admin_users` add unique `admin_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 767 bytes
因為laravel默認使用utf8mb4字符集完箩,utf8mb4是每一字符用4位表示繁扎,可以很好的支持emoji表情存存入數(shù)據(jù)庫的問題
每個字符4為那么咖城,總?cè)萘烤蜕傩┙隳牛瑄tf8最大是255漱挎,255*3 = 765受楼;765/4 = 191.25, 所以utf8mb4最大支持191個字符垦搬,如果字段長度超過191,那么就會出現(xiàn)上述錯誤提示艳汽。
有兩種方法可以解決
方法一:修改默認字符字段長度(官方解決方案)
//edit your AppServiceProvider.php file contains in providers folder
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
此方法必須保證每個string字段長度小于等于191猴贰,如果大于191是一樣會報錯的,作者就是因為修改上面的代碼后河狐,沒有修改字段長度米绕,一直不能正常migrate
方法二:修改為utf8字符集
Go to /config/database.php and find these lines
'mysql' => [
...,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
...,
'engine' => null,
]
and change them to:
'mysql' => [
...,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
...,
'engine' => 'InnoDB',
]
在config/database.php中,將charset和collation分別改為'utf8' 和 'utf8_unicode_ci'
因為utf8最大支持255馋艺,所以在191 - 255之間都是可以的栅干。