登录
首页 >  Golang >  Go问答

UUID 外键在 Gorm 中的使用

来源:stackoverflow

时间:2024-02-28 08:27:24 421浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《UUID 外键在 Gorm 中的使用》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正在尝试使用 gorm 在两个数据库表之间创建属于关系,我的代码如下:

type shop struct {
    id    uuid.uuid `json:"id" gorm:"primarykey;type:uuid"`
    name  string    `json:"name" gorm:"not null" validate:"required"`
    city  string    `json:"city" gorm:"not null" validate:"required"`
    state string    `json:"state" gorm:"not null" validate:"required"`
}
type employee struct {
    id        uuid.uuid `json:"id" gorm:"primarykey;type:uuid"`
    firstname string    `json:"first_name" gorm:"not null" validate:"required"`
    lastname  string    `json:"last_name" gorm:"not null" validate:"required"`
    email     string    `json:"email" gorm:"not null;unique" validate:"required,email"`
    password  string    `json:"password" gorm:"not null" validate:"required"`
    active    bool      `json:"active" gorm:"not null;default:false"`
    shopid    uuid.uuid `json:"shop_id" gorm:"type:uuid"`
    shop      shop      `gorm:"foreignkey:shopid"`
}

当我运行迁移时,会弹出此错误:

[error] invalid field found for struct .../.../.../api/models.Employee's field Shop: define a valid foreign key for relations or implement the Valuer/Scanner interface

我发现了一些使用数字主键的参考文献,它们似乎工作正常,但我找不到任何使用 uuid 的解决方案...


正确答案


我不确定,但我对消息错误的理解是 uuid.uuid 类型没有实现 valuer 和 scanner 接口的方法。

您应该创建自己的类型 uuid,可以是这样的:

type uuid uuid.uuid

func(id uuid) value() (driver.value, error) {   
    return id.string(), nil
}

func (id *uuid) scan(value interface{}) error {
    dbid, ok := value.(string)
    if !ok {
        return errors.new("id scan: invalid value")
    }
    
    
    *e = uuid.mustparse(dbid)
    return nil
}

并将其用于结构的定义:

type Shop struct {
    ID    UUID `json:"id" gorm:"primaryKey;type:uuid"`
    //...
}

终于介绍完啦!小伙伴们,这篇关于《UUID 外键在 Gorm 中的使用》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>