在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


当前回答

腔:

添加到。env文件

DB_ENGINE=InnoDB

其他回答

我认为强制stringlength到191是一个非常糟糕的主意。 所以我去调查了解到底发生了什么。

我注意到这个消息错误:

SQLSTATE[42000]:语法错误或访问违规:1071指定的键 太长了;最大密钥长度为767字节

在我更新MySQL版本后开始出现。所以我已经用PHPMyAdmin检查了表,我注意到所有创建的新表都带有utf8mb4_unicode_ci,而不是旧表的utf8_unicode_ci。

在我的doctrine配置文件中,我注意到charset被设置为utf8mb4,但我之前的所有表都是在utf8中创建的,所以我猜这是一些更新魔术,它开始在utf8mb4上工作。

现在最简单的解决方法是更改ORM配置文件中的行字符集。 然后使用utf8mb4_unicode_ci删除表(如果您在dev模式下),或者如果您不能删除它们则修复字符集。

Symfony 4

在config/packages/doctrine.yaml中将字符集:utf8mb4修改为字符集:utf8

现在我的理论迁移又开始起作用了。

需要使用以下命令创建数据库。

CREATE DATABASE database_name CHARACTER SET utf8 COLLATE utf8_general_ci;

然后运行以下命令迁移数据库表。

php artisan migrate

如果您想在AppServiceProvider中进行更改,那么您需要在迁移中定义电子邮件字段的长度。只需将第一行代码替换为第二行。

create_users_table

$table->string('email')->unique();
$table->string('email', 50)->unique();

create_password_resets_table

$table->string('email')->index();
$table->string('email', 50)->index();

在成功更改之后,您可以运行迁移。 注意:首先你必须从数据库中删除(如果你有)users表,password_resets表,并从迁移表中删除users和password_resets条目。

我得到了这个错误尽管我已经有了(实际上因为我已经有了) 模式:defaultStringLength (191);在AppServiceProvider.php文件中。

原因是我试图在我的一个迁移中设置一个高于191的字符串值:

Schema::create('order_items', function (Blueprint $table) {
    $table->primary(['order_id', 'product_id', 'attributes']);
    $table->unsignedBigInteger('order_id');
    $table->unsignedBigInteger('product_id');
    $table->string('attributes', 1000); // This line right here
    $table->timestamps();
});

删除1000或将其设置为191解决了我的问题。

对于这个错误,我找到了两个解决方案

选项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);
}