mysql - 创建通知表时 Laravel "Specified key was too long"

标签 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();
    });
}

但是我在尝试使用它时遇到错误:

[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并运行低于 5.7.7 版本的 MySQL 版本。您可以通过在 AppServiceProvider 类的 boot 方法中调用 Schema::defaultStringLength 方法来解决此问题。

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

关于mysql - 创建通知表时 Laravel "Specified key was too long",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600753/

相关文章:

php - Laravel 如何将两个查询结果合并到一个对象中

php - 同一模型上 Eloquent 亲子关系

php - 从 Laravel 5.2 中的大数据库查询中排除结果的最佳方法

php - 有没有办法在自定义\Illuminate\Contracts\Validation\Rule 中使用参数

php - 如果字符串已存在,则在字符串后添加数字

php - 数据未插入到php中的mysql数据库中

mysql - 轨道 4 : model relationships and indexing for two has_many through models

php - 更改 "Whoops, looks like something went wrong."消息

laravel - 无法在 Laravel 5.2 的数据库中存储 session

php - MySQL 查询中 Wordpress 中的独特 slug