laravel migration中的唯一值对字符串无效

问题描述 投票:0回答:1

我正在使用laravel,我想使用迁移,但是laravel artisan说:

Migrating: 2014_10_12_000000_create_users_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 `users` ad
d unique `users_username_unique`(`username`))

我的代码是:

if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id')->unsigned();
                $table->string('name');
                $table->string('username')->unique();
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });
        }
php laravel migration
1个回答
1
投票

正如错误消息所暗示的那样,DB的唯一键太长。

您可以在Laravel迁移中命名您的唯一索引,如下所示:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id')->unsigned();
    $table->string('name');
    $table->string('username');
    $table->string('email');
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
    $table->unique('username', 'username');
    $table->unique('email', 'email');
});

这样,username的唯一索引将命名为username而不是users_username_unique,因此,不会超过索引名称的字节限制

© www.soinside.com 2019 - 2024. All rights reserved.