最近在研究Laravel,在使用Migrate工具生成数据表的时候,连使用自带的User表的Migration生成数据表结构的时候都会报错
报错内容类似于:
Illuminate\Database\QueryException : 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`)) at D:\IMBA Group\DaShang\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) { > 664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668| Exception trace: 1 Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes") D:\IMBA Group\DaShang\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:143 2 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes") D:\IMBA Group\DaShang\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:141 Please use the argument -v to see more details.
在报错里可以看出是因为Migration里某处的字段长度太长了(Specified key was too long),在网上查了很多资料都无法解决
本地环境:
- MySQL: 5.7.11 (可以正常使用utf8mb4,但仍然报错)
- Laravel: 5.6
这里提供两个方法,选其一即可
1.在AppServiceProvider的Boot引导时指定默认字符串长度:
在Boot方法里添加 Schema::defaultStringLength(191); 并且在上面引用 Illuminate\Support\Facades\Schema 这个类
具体方法:
use Illuminate\Support\Facades\Schema; function boot() { Schema::defaultStringLength(191); }
2.手动指定默认字符串长度:
网上很多资料都是相互转载的,有让把 /config/database.php 里的charset改为utf8,个人试过无效。也有让修改AppServiceProvider.php的StringDefaultLength的,也无效。
最后在Github的一张issue([5.4] SQL error when migrating tables #17508)里找到解决方法。
把添加字段的链式里的->unique(); 删去,在结尾加上
$table->index([DB::raw('email(191)')]);//更改`email`字段为index,长度:191 $table->unique([DB::raw('email(191)')]);//更改`email`字段为unique,长度:191
最后这个Migration就会变成这样
public function up() { Schema::table('users', function (Blueprint $table) { // $table->string('email'); $table->unique([DB::raw('email(191)')]); }); }
成功
0 条评论
与博主谈论人生经验?