在Laravel 5.4上使用php artisan make:auth迁移错误
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl e 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
如果您运行“php artisan migrate”时出现此错误。你可以这样修改你想要更新的表:
DB::statement('ALTER TABLE table_name ROW_FORMAT = DYNAMIC;');
在迁移脚本中。例子:
class MyMigration extends Migration {
/**
* Run the migrations.
*/
public function up()
{
DB::statement('ALTER TABLE table_name ROW_FORMAT = DYNAMIC;');
Schema::table('table_name', function ($table) {
//....
});
}
/**
* Undo the migrations.
*/
public function down()
{
//....
}
}
然后再次运行php artisan migrate
对于不想更改AppServiceProvider.php的人。
(在我看来,仅仅为了迁移而更改AppServiceProvider.php是一个坏主意)
您可以将数据长度添加回database/migrations/下的迁移文件,如下所示:
create_users_table.php
$table->string('name',64);
$table->string('email',128)->unique();
create_password_resets_table.php
$table->string('email',128)->index();
对于这个错误,我找到了两个解决方案
选项1:
打开database/migrations文件夹下的user和password_reset表
只需要改变邮件的长度:
$table->string('email',191)->unique();
选项2:
打开app/Providers/AppServiceProvider.php文件,在boot()方法中设置一个默认字符串长度:
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Laravel 5.4由数据库版本导致。
根据文档(在索引长度和MySQL / MariaDB部分):
Laravel默认使用utf8mb4字符集,其中包括
支持在数据库中存储“表情包”。如果你正在运行一个
MySQL版本高于5.7.7或MariaDB版本高于5.7.7
对于10.2.2版本,您可能需要手动配置默认值
由迁移生成的字符串长度,以便MySQL创建
它们的索引。方法进行配置
方案::defaultStringLength方法在你的AppServiceProvider。
换句话说,在<ROOT>/app/Providers/AppServiceProvider.php:
// Import Schema
use Illuminate\Support\Facades\Schema;
// ...
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Add the following line
Schema::defaultStringLength(191);
}
// ...
}
但正如另一个答案的评论所说:
注意这个解决方案。例如,如果您索引电子邮件字段,
存储邮件的最大长度为191个字符。这个更少
比RFC官方声明的要多。
因此,文档还提出了另一种解决方案:
或者,您可以启用innodb_large_prefix选项
数据库。有关的说明,请参阅数据库的文档
如何正确启用此选项。