登录
首页 >  Golang >  Go问答

使用GORM自定义连接表的创建时间字段

来源:stackoverflow

时间:2024-02-14 20:21:26 413浏览 收藏

大家好,今天本人给大家带来文章《使用GORM自定义连接表的创建时间字段》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在尝试自定义many2many表连接。我有两个表,我想从中获取 id,并需要另一个字段,该字段将告诉我连接表中的条目何时创建。 id 正常,但“created_at”没有更新,并且显示“null”而不是时间。

// this is the table join struct which I want to make
type UserChallenges struct {
    gorm.JoinTableHandler
    CreatedAt   time.Time
    UserID      int
    ChallengeID int
}

//hook before create
func (UserChallenges) BeforeCreate(Db \*gorm.DB) error {
    Db.SetJoinTableHandler(&User{}, "ChallengeId", &UserChallenges{})
    return nil
}

这不会在构建时给出任何错误。请告诉我缺少什么,以便我可以获得其中的创建时间字段。

ps - gorm.io 上的 gorm 文档仍然显示 setupjointable 方法,但在新版本中已弃用。有一个 setjointablehandler 但没有任何可用的文档。


解决方案


使用连接表模型需要注意的是,如果您想访问模型内​​的字段,则必须显式查询它。

即使用 db.model(&user{id: 1}).association("challenges").find(&challenges)db.preload("challenges").find(&users) 等将只是为您提供关联结构的集合,并且在这些集合中没有地方可以放置额外的字段!

为此你会这样做:

joins := []userchallenges{}
db.where("user_id = ?", user.id).find(&joins)
// now joins contains all the records in the join table pertaining to user.id,
// you can access joins[i].createdat for example.

如果您还想检索挑战,您可以修改连接结构以将其与挑战的 belongsto 关系集成并预加载:

type UserChallenges struct {
    UserID      int `gorm:"primaryKey"`
    ChallengeID int `gorm:"primaryKey"`
    Challenge   Challenge
    CreatedAt   time.Time
}

joins := []UserChallenges{}
db.Where("user_id = ?", user.ID).Joins("Challenge").Find(&joins)
// now joins[i].Challenge is populated 

今天关于《使用GORM自定义连接表的创建时间字段》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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