如何为多列创建唯一约束?

How do I create unique constraint for multiple columns?

我有以下结构并想在(用户 ID 和联系人)上创建唯一索引。这在 gorm 中可行吗?

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

我想创建table类似

的东西
CREATE TABLE contact (...column definitions ...) 
    CONSTRAINT constraint1
    UNIQUE (user_id, contact) 

models 上的文档为 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"`
}