Gorm:pq 重复键违反唯一约束

Gorm: pq duplicate key violates unique constraint

我目前正在努力学习 go & Gorm,所以如果我遗漏了一些明显的东西,我深表歉意。

我已经声明了以下 GORM 模型

type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              string `gorm:"unique"`
    SteamID64            uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}

type DeepLink struct {
    gorm.Model
    ShortURL   string `gorm:"unique"`
    UserID     uint
    User       User
    LinkAction Action
    Payload    interface{} `gorm:"-"`
}

我希望能够识别创建深层链接的用户 - 这可能不是执行此操作的最佳方法。

在新数据库上,使用

创建第二个用户时
func (m *Models) CreateUserFromDiscord(discordID, discordNickname, discordProfilePicURL string) *User {
    u := &User{
        DiscordID:            discordID,
        DiscordNickname:      discordNickname,
        DiscordProfilePicURL: discordProfilePicURL,
    }

    m.db.Create(u)
    return u
}

我收到一条错误消息 pq: duplicate key value violates unique constraint "users_steam_id_key"

使用此方法创建第一个用户并为此用户创建深层链接工作正常,但创建第二个用户会引发错误。两个用户都没有设置 SteamID。

我想知道是否有任何方法可以解决这个问题或更好地构建我的模型来解决这个问题。

数据库是使用 Gorms AutoMigrate 功能创建的。这发生在一个新的 db

谢谢

在 golang 中,如果您没有为 String 变量设置值,则意味着它的值为“”(空字符串)。 Ref

由于您没有设置 SteamID,因此将“”(空字符串)设置为第一个用户的值。 然后,当您尝试将第二个用户 SteamID 列保存为“”(空)时,则违反了唯一约束,因为“”(空字符串)不是数据库的空值,并给您错误。

解决方案:对结构中的那些字段使用*(指针)。如果未设置 *string/*int64 变量,则其值为 nil。还使可选列在数据库中可为空。

type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              *string `gorm:"unique"`
    SteamID64            *uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}