简体   繁体   English

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

[英]How do I create unique constraint for multiple columns?

I have following structure and would like to create unique index on (UserId and Contact).我有以下结构,想在(UserId 和 Contact)上创建唯一索引。 Is this possible in gorm?这在gorm中可能吗?

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

I would like to create table something like我想创建类似的表

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

The doc on models specifies the following for INDEX and UNIQUE_INDEX :模型文档为INDEXUNIQUE_INDEX指定以下内容:

INDEX Create index with or without name, same name creates composite indexes INDEX 创建有名或无名索引,同名创建复合索引

UNIQUE_INDEX Like INDEX, create unique index UNIQUE_INDEX 和 INDEX 一样,创建唯一索引

This means that two fields with the same UNIQUE_INDEX name will create a composite unique index.这意味着具有相同UNIQUE_INDEX名称的两个字段将创建一个复合唯一索引。

The full struct definition to use a composite index named compositeindex using your example becomes:使用您的示例使用名为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"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM