0

在我的 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 表中添加 slug 字段:

    $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 ->default('rt_genres.id') ?

2) 当我在我的应用程序中使用 "cviebrock/eloquent-sluggable": "^4.5" 插件时,将 public.rt_genre_translations.name 分配给 slug 值会很酷吗?我可以做吗 ?

谢谢!

4

1 回答 1

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');
});
于 2018-09-04T22:31:16.433 回答