mysql laravel迁移-列类型longText的独特组合

mrphzbgm  于 5个月前  发布在  Mysql
关注(0)|答案(3)|浏览(56)

我有一个表,它的列如下所示:

...
$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


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

np8igboo

np8igboo1#

最后,我找到了一种解决方案,因为我需要一个唯一的索引在一个像列的文本上与其他列结合起来,在迁移中使用DB::unprepared方法似乎是一个可能的解决方案。
所以我创建了一个名为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`');
    }
}

字符串
迁移使其成功运行。

wlwcrazw

wlwcrazw2#

如果你改变:`

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

字符串
收件人:

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


它将工作,但我不知道如果你期望更长的标题(200)文本..

zqry0prt

zqry0prt3#

我不知道你是否还需要答案,但我是这样做的:

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

字符串
当然10可以设置为任何你需要的长度

相关问题