迁移以用默认值填充段

时间:2018-09-04 12:39:00

标签: postgresql laravel-5 slugify

在我的Laravel 5.6 / PostgreSQL 10.5应用程序中 我有2张桌子:

CREATE TABLE public.rt_genres (
    id serial NOT NULL,
    published bool NULL DEFAULT false,
    created_at timestamp NOT NULL DEFAULT now(),
    updated_at timestamp NULL,
    CONSTRAINT rt_genres_pkey PRIMARY KEY (id)
)...

CREATE TABLE public.rt_genre_translations (
    id serial NOT NULL,
    genre_id int4 NOT NULL,
    "name" varchar(100) NOT NULL,
    description text NOT NULL,
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    locale varchar(2) NOT NULL,
    CONSTRAINT genre_translations_genre_id_locale_unique UNIQUE (genre_id, locale),
    CONSTRAINT rt_genre_translations_pkey PRIMARY KEY (id),
    CONSTRAINT genre_translations_genre_id_foreign FOREIGN KEY (genre_id) REFERENCES rt_genres(id) ON DELETE CASCADE
)

我需要在第一个rt_genres表中添加子弹字段 带有迁移规则:

    $table->string('slug', 105)->unique();

出现错误:

: Unique violation: 7 ERROR:  could not create unique index "genres_slug_unique"                                          
DETAIL:  Key (slug)=(id) is duplicated.")

1)如果有一种方法可以在迁移中分配一些唯一的默认值,例如= id ->默认值('rt_genres.id') ?

2)当我使用时,从public.rt_genre_translations.name分配子弹值会很酷 “ cviebrock / eloquent-sluggable”:我的应用程序中的“ ^ 4.5”插件?我可以吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您只能使用触发器(SO answer)从其他列中获取默认值。

您可以使列nullable

$table->string('slug', 105)->nullable()->unique();

或者您创建列,插入唯一值,然后创建索引:

Schema::table('rt_genres', function($table) {
    $table->string('slug', 105);
});
DB::table('rt_genres')->update(['slug' => DB::raw('"id"')]);
Schema::table('rt_genres', function($table) {
    $table->unique('slug');
});
相关问题