【问题标题】:laravel migration Specified key was too long; max key length is 767 bytes [duplicate]laravel migration 指定的key太长;最大密钥长度为 767 字节 [重复]
【发布时间】:2019-02-21 13:00:09
【问题描述】:

我正在尝试迁移 laravel 迁移,但出现错误:

Migrating: 2014_10_12_100000_create_password_resets_table

   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 `password_
resets` add index `password_resets_email_index`(`email`))

我的代码是:

if (!Schema::hasTable('password_resets')) {
            Schema::create('password_resets', function (Blueprint $table) {
                $table->string('email')->index();
                $table->string('token');
                $table->timestamp('created_at')->nullable();
            });
        }

【问题讨论】:

    标签: laravel migration


    【解决方案1】:

    你可以手动设置字符串长度

    $table->string('name', 191); // You can put any number in exchange of 191
    

    否则

    把这个放到APP -> Providers -> AppServiceProvider

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

    【讨论】:

    • 我做了一些研究,发现了不同的观点。由于在用户表的电子邮件字段中使用了“唯一”索引,因此会出现此问题。所以简单地增加一个250的极限值就可以解决问题。这个值被添加到文件迁移中,它在代码“unique ()”的行上创建用户表,所以它看起来像这样:$table->string('email', 250)->unique ();跨度>
    • 这是一个丑陋的 hack,只适用于昨天需要在生产中修复的遗留 Laravel 项目。它将在未来产生问题。正确的解决方案是升级到最新版本的 MySQL 和/或修复数据库配置以支持 Laravel 使用的 utf8mb4 字符集。
    • @AndrewKoster 如果您阅读答案日期,您会知道当时可用的版本是最新的 laravel 5.6
    • 在 laravel 8.0 中工作
    【解决方案2】:

    你应该在AppServiceProvider的boot方法中设置默认字符串长度为191

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

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2016-04-15
      • 2012-05-31
      • 2015-06-22
      • 1970-01-01
      • 2013-12-21
      • 2015-06-29
      • 2016-10-04
      • 2017-12-30
      相关资源
      最近更新 更多