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

mrphzbgm  于 2024-01-05  发布在  Mysql
关注(0)|答案(3)|浏览(176)

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

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

字符串
我需要一个基于这些列的组合唯一索引。但“title”是一个longText。
这一个不起作用:

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


迁移工具sais:

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


这一条也不管用:

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


迁移工具sais:

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


这一条也不管用:

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


迁移工具sais:

  1. [Illuminate\Database\QueryException]
  2. 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的类,如下所示:

  1. <?php
  2. use Illuminate\Support\Facades\Schema;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Database\Migrations\Migration;
  5. class AddUniquesToEvents extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public function up()
  13. {
  14. DB::unprepared('ALTER TABLE timeline_events
  15. ADD UNIQUE key u_title_and_dates (title(64),start_year, start_month,start_day)'
  16. );
  17. }
  18. /**
  19. * Reverse the migrations.
  20. *
  21. * @return void
  22. */
  23. public function down()
  24. {
  25. DB::unprepared('ALTER TABLE timeline_events drop index `u_title_and_dates`');
  26. }
  27. }

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

展开查看全部
wlwcrazw

wlwcrazw2#

如果你改变:`

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

字符串
收件人:

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


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

zqry0prt

zqry0prt3#

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

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

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

相关问题