我具有以下结构,并想在(UserId和Contact)上创建唯一索引。在gorm中这可能吗?

type Contact struct {
    gorm.Model
    UserId    uint   `gorm:"index;not null"`
    Contact string `gorm:"type:text;not null"`
}

我想创建类似表

CREATE TABLE contact (...column definitions ...) 
    CONSTRAINT constraint1
    UNIQUE (user_id, contact) 
分析解答

楷模上的文档为INDEXUNIQUE_INDEX指定了以下内容:

INDEX Create index with or without name, same name creates composite indexes

UNIQUE_INDEX Like INDEX, create unique index

这意味着具有相同UNIQUE_INDEX名称的两个字段将创建一个复合唯一索引。

在您的示例中,使用名为compositeindex的复合索引的完整结构定义变为:

type Contact struct {
    gorm.Model
    UserId    uint   `gorm:"UNIQUE_INDEX:compositeindex;index;not null"`
    Contact   string `gorm:"UNIQUE_INDEX:compositeindex;type:text;not null"`
}