创建通知表时,Laravel"指定密钥太长"

nan*_*eri 5 mysql laravel laravel-5

我正在使用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();
    });
}
Run Code Online (Sandbox Code Playgroud)

但是在尝试使用它时出现错误:

[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
Run Code Online (Sandbox Code Playgroud)

更新

我将索引列的名称更改为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
Run Code Online (Sandbox Code Playgroud)

Mah*_*bub 8

如果您使用的是Laravel 5.4并运行早于5.7.7版本的MySQL版本.您可以通过Schema::defaultStringLengthAppServiceProvider类的boot方法中调用方法来解决此问题.

public function boot()
{
    Schema::defaultStringLength(191);
}
Run Code Online (Sandbox Code Playgroud)

  • 它在Laravel 5.4.21中不起作用.您应该使用`Illuminate\Database\Schema\Builder :: $ defaultStringLength = 191`代替. (2认同)