laravel migration - 列类型longText的唯一组合

时间:2017-11-23 10:47:12

标签: php mysql laravel unique-index longtext

我有一张像这样的柱子的桌子:

...
$table->longText('title')->comment('Event title');
$table->decimal('start_year',13,0)->nullable(true)->comment('Year part of beginning of event date');
$table->decimal('start_month',2,0)->default(0)->comment('Month part of beginning of event date');
$table->decimal('start_day',2,0)->default(0)->comment('Day part of beginning of event date');
...

我需要一个基于这些列的组合唯一索引。但是' title'是一个longText。

这个不起作用:

$table->unique([['title','255'], 'start_year', 'start_month', 'start_day'],'unique_title_and_date');

迁移工具sais:

[ErrorException]
  strtolower() expects parameter 1 to be string, array given

这个也不起作用:

$table->unique(['title(255)', 'start_year', 'start_month', 'start_day'],'unique_title_and_names');

迁移工具sais:

  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'title(255)' doesn't exist in table

这个也不起作用:

$table->unique(['title', 'start_year', 'start_month', 'start_day'],'unique_title_and_names');

迁移工具sais:

[Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1170 BLOB/TEXT column 'title' used in key specification without a key length 

如何让迁移工具吃这个命令?

2 个答案:

答案 0 :(得分:1)

最后我找到了一种解决方案。 因为我需要在列与其他列结合使用的文本上使用唯一索引,所以在迁移中使用DB :: unrepared方法似乎是一种可能的解决方案。

所以我创建了一个名为AddUniquesToEvents的类,如下所示:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUniquesToEvents extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         DB::unprepared('ALTER TABLE timeline_events
                                ADD UNIQUE key u_title_and_dates (title(64),start_year, start_month,start_day)'
                          );
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
       DB::unprepared('ALTER TABLE timeline_events drop index `u_title_and_dates`');
    }
}

迁移使其成功运行。

答案 1 :(得分:0)

如果你改变:`

$table->longText('title')->comment('Event title');

为:

$table->string('title',200)->comment('Event title');

它会起作用,但我不知道你是否期望有更长(200)文字的标题..