首页 > 解决方案 > 如何解决这个 laravel 迁移错误创建数据库表?

问题描述

我正在尝试在 laravel 中迁移数据库,如果我要添加,则会index()出现migration/2014_10_12_100000_create_password_resets_table.php 这样的错误

My-PC MINGW64 /c/xampp/htdocs/ecoprotect
$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
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 k
ey length is 767 bytes (SQL: alter table `password_resets` add index `password_resets_email_index`(`email`))

  at C:\xampp\htdocs\ecoprotect\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 by
tes")
      C:\xampp\htdocs\ecoprotect\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\ecoprotect\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

这是我的代码迁移/2014_10_12_100000_create_password_resets_table.php:

<?php

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

class CreatePasswordResetsTable extends Migration
{
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }
}

标签: phplaravelmigration

解决方案


我找到了两个解决这个错误的方法。

选项1:

数据库/迁移文件夹中打开您的用户密码重置表

只需更改电子邮件的长度:

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

选项 2:

如果您想限制项目中每个字符串的长度,请遵循此

打开您的app/Providers/AppServiceProvider.php文件并在boot()方法内设置默认字符串长度:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

推荐阅读