【问题标题】:Laravel 5.7 Migration : key was too longLaravel 5.7 迁移:密钥太长
【发布时间】:2019-05-17 04:06:06
【问题描述】:

我想创建一个多个唯一的列,但是当我运行php artisan migrate 时,我得到了这个错误:

SQLSTATE[42000]:语法错误或访问冲突:1071 指定键 太长了;最大密钥长度为 1000 字节

这是我的代码:

Schema::create('buku', function (Blueprint $table) {
        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit',4);
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();

        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });

这个AppServiceProvider.php 文件

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

我们将不胜感激

版本:Laravel 5.7

[已解决]

我通过添加$table->engine = 'innoDB'; 解决了这个问题,因此代码如下所示:

Schema::create('buku', function (Blueprint $table) {
        $table->engine = 'innoDB';

        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit');
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();
        
        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });

然后重新迁移它,一切都很好。

【问题讨论】:

  • 请添加您的解决方案作为答案,然后自行接受。然后根据您的问题编辑您的答案。谢谢

标签: php laravel migration


【解决方案1】:

app/Providers/AppServiceProvider.php文件中添加以下代码

use Illuminate\Support\Facades\Schema;

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

注意:启动方法已经有了,所以你只需要在里面添加Schema::defaultStringLength(191);,然后删除旧表并重新迁移

【讨论】:

    【解决方案2】:

    您正在尝试 4 列的唯一索引。 4 列之和最多可包含 191 个字符。尝试使用 47 个字符的每一列。

    Schema::create('buku', function (Blueprint $table) {
        $table->engine = 'innoDB';
    
        $table->increments('id');
        $table->string('judul', 47);
        $table->string('pengarang', 47);
        $table->string('penerbit', 47);
        $table->string('thn_terbit', 47);
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();
    
        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-14
      • 2017-02-25
      • 2019-04-22
      • 2019-07-31
      • 2021-03-13
      • 1970-01-01
      • 2015-07-22
      • 2014-07-10
      相关资源
      最近更新 更多