我正在使用Laravels的默认迁移来创建通知表。

public function up()
{
    Schema::create('notifications', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('type');
        $table->morphs('notifiable');
        $table->text('data');
        $table->timestamp('read_at')->nullable();
        $table->timestamps();
    });
}

但是尝试使用它时出现错误:
[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 `notifications` add index `n
  otifications_notifiable_id_notifiable_type_index`(`notifiable_id`, `notifiable_type`))



  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes



  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

更新

我将索引列的名称更改为notifiable_index,但它仍然提示索引键的长度。
  [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 `notifications` add index `n
  otifiable_index`(`notifiable_id`, `notifiable_type`))



  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes



  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

最佳答案

如果您使用的是Laravel 5.4并运行的MySQL版本低于5.7.7发行版。您可以通过在Schema::defaultStringLength类的AppServiceProvider方法中调用boot方法来解决此问题。

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

10-06 01:42