今天在执行laravel migrate时出现异常,找了好半天才找到问题所在,特此记录一下。
配好数据库,执行 ``` php artisan migrate ```。但是遇到了问题:
migrations中up函数为:
public function up()
{
Schema::create(‘users‘, function (Blueprint $table) {
$table->increments(‘id‘);
$table->string(‘name‘);
$table->string(‘email‘)->unique();
$table->string(‘password‘);
$table->rememberToken();
$table->timestamps();
});
}
执行
E:\work\www\blog>php artisan migrate
出现异常:
Migration table created successfully.
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
网上也没查不明所以,在 stackoverflow上有人说跟数据库引擎有关(InnoDB 的 key 支持 767 字节,而 MyISAM 支持 1000 字节。) (http://stackoverflow.com/questions/1814532/1071-specified-key-was-too-long-max-key-length-is-767-bytes)。
但是我尝试了 MyISAM 仍然报同样错误,只是 767 变为了 1000。
后来我在数据库配置文件发现了端倪 ```config/database.php``` (laravel版本为5.4):
老的 5.3
```php
‘mysql‘ => [
‘driver‘ => ‘mysql‘,
‘host‘ => env(‘DB_HOST‘, ‘localhost‘),
‘port‘ => env(‘DB_PORT‘, ‘3306‘),
‘database‘ => env(‘DB_DATABASE‘, ‘forge‘),
‘username‘ => env(‘DB_USERNAME‘, ‘forge‘),
‘password‘ => env(‘DB_PASSWORD‘, ‘‘),
‘charset‘ => ‘utf8‘,
‘collation‘ => ‘utf8_unicode_ci‘,
‘prefix‘ => ‘‘,
‘strict‘ => true,
‘engine‘ => null,
],
```
新的 5.4
```php
‘mysql‘ => [
‘driver‘ => ‘mysql‘,
‘host‘ => env(‘DB_HOST‘, ‘127.0.0.1‘),
‘port‘ => env(‘DB_PORT‘, ‘3306‘),
‘database‘ => env(‘DB_DATABASE‘, ‘forge‘),
‘username‘ => env(‘DB_USERNAME‘, ‘forge‘),
‘password‘ => env(‘DB_PASSWORD‘, ‘‘),
‘charset‘ => ‘utf8mb4‘,
‘collation‘ => ‘utf8mb4_unicode_ci‘,
‘prefix‘ => ‘‘,
‘strict‘ => true,
‘engine‘ => null,
],
```
发现没 laravel 5.4 开始使用 utf8mb4 数据库字符集了。这个字符集在 MySQL 5.5.3 开始支持。
[utf8 和 utf8mb4 区别看这里](http://ourmysql.com/archives/1402)
如是将 ``` config/database.php ``` 改为
```
‘charset‘ => ‘utf8‘,
‘collation‘ => ‘utf8_unicode_ci‘,
```
重新执行``` php artisan migrate ```,success!