最近在学习docker,刚好配好了mysql5.6.39,然后最近在接触学习laravel5.5,所以就直接用了这里的docker里面的数据库来进行练习,然后遇到了两个坑。
1.Laravel 5.5默认使用utf8mb4字符编码,而不是之前的utf8编码。因此运行php artisan migrate 会出现如下错误:
[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
原因:
Laravel 默认使用 utf8mb4 字符,它支持在数据库中存储「emojis」。如果你是在版本低于5.7.7 的 MySQL release 或者版本低于10.2.2 的 MariaDB release 上创建索引,那就需要你手动配置迁移生成的默认字符串长度。
解决方案:
a.创建数据库时直接设置utf8mb4-unicode_ci字符(这种情况是在mysql5.5.3后才可以设置)
b.手动配置迁移命令migrate生成的默认字符串长度,在AppServiceProvider中调用Schema::defaultStringLength方法来实现配置:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
classAppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/publicfunction boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* @return void
*/publicfunction register()
{
// }
}
2.SQLSTATE[HY000] [2002] Connection refused (SQL: select count(*) as aggregate from `users` where `email` =
数据库配置如下:
"driver" => "mysql"
"host" => "127.0.0.1"
"port" => "6606"
"database" => "laravel-5.5"
"username" => "root"
"password" => "***"
"unix_socket" => ""
"charset" => "utf8mb4"
"collation" => "utf8mb4_unicode_ci"
"prefix" => ""
"strict" => true
"engine" => null
"name" => "mysql"
解决方案:
然后各种搜索各种找,才发现是数据库的ip对不上,然后把host改成当前机器的ip就好了
网友评论