【问题标题】:SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytesSQLSTATE[42000]:语法错误或访问冲突:1071 指定的键太长;最大密钥长度为 767 字节
【发布时间】:2019-10-11 23:21:56
【问题描述】:

在cmd中提交“php artisan migrate:fresh”后报错。

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

SQLSTATE[42000]:语法错误或访问冲突:1071 指定的键太长;最大密钥长度为 767 字节(SQL:alter table users add unique users_email_unique(email))

【问题讨论】:

  • 是的,任何人都可以通过 Google 轻松找到该链接。问题是该链接正在解释遗留代码的丑陋解决方法。当您在使用最新的 Laravel 项目时遇到此错误时,此链接只会告诉您如何阻止代码以避免修复 DB 服务器。

标签: mysql laravel


【解决方案1】:

编辑:仅供参考...如果您使用的是 MySQL 8.0,此软件包的 v4 会在迁移中添加一些唯一索引,需要 125 而不是 191。 (MariaDB 不需要这些)。

【讨论】:

    【解决方案2】:

    来自这个链接:https://laravel-news.com/laravel-5-4-key-too-long-error

    对于那些运行 MariaDB 或旧版本 MySQL 的用户,您可以点击这里 尝试运行迁移时出错

    如迁移指南中所述,要解决此问题,您只需 编辑您的 AppServiceProvider.php 文件并在启动方法中设置一个 默认字符串长度:

    use Illuminate\Support\Facades\Schema;
    
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
    

    之后一切都应该正常工作了。

    请注意,根据 Andrew Koster 在下面的评论,这可能只是针对遗留代码的解决方案。您可能希望为最新项目研究不同的解决方案。

    【讨论】:

    • 我真的认为这是访问量最大的 laravel 新闻文章:D
    • 它简洁实用,解决了版本升级问题。所以它的排名可能相当高。
    • 这有什么缺点?
    • 它只对遗留代码有用。对于任何最新的 Laravel 项目,当您可以修复过时的数据库时,这是一种在未来制造问题的方法。
    猜你喜欢
    • 2018-09-28
    • 2021-02-28
    • 2018-09-15
    • 2017-07-03
    • 2017-09-09
    • 2017-04-01
    • 2015-06-22
    • 2013-12-21
    • 2015-06-29
    相关资源
    最近更新 更多