How to specify unique together index in gorm?

huangapple go评论116阅读模式
英文:

How to specify unique together index in gorm?

问题

我现在是你的中文翻译助手,以下是翻译好的内容:

  1. type ABC struct {
  2. ID uint
  3. Abc int `gorm:"uniqueIndex"`
  4. Bcd string `gorm:"uniqueIndex"`
  5. }

我希望字段 AbcBcd 在一起是唯一的。

{Abc: 1, Bcd: "hello"}{Abc: 1, Bcd: "hi"} 应该是有效的,但是

{Abc: 1, Bcd: "hello"}{Abc: 1, Bcd: "hello"} 应该是无效的。

英文:
  1. type ABC struct {
  2. ID uint
  3. Abc int `gorm:"unidqueIndex;
  4. Bcd string
  5. }

I want Field Abc and Bcd to be unique together

{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hi"} should be valid but

{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hello"} should be invalid

答案1

得分: 1

给这两个字段设置相同的索引名称。

  1. type ABC struct {
  2. ID uint
  3. Abc int `gorm:"uniqueIndex:abc_bcd_uniq"`
  4. Bcd string `gorm:"uniqueIndex:abc_bcd_uniq"`
  5. }

请参考GORM文档中的复合索引部分

英文:

Give both fields the same index name.

  1. type ABC struct {
  2. ID uint
  3. Abc int `gorm:"uniqueIndex:abc_bcd_uniq"`
  4. Bcd string `gorm:"uniqueIndex:abc_bcd_uniq"`
  5. }

See composite indexes in the GORM docs.

huangapple
  • 本文由 发表于 2022年7月8日 04:44:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/72904014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定