【问题标题】:"Creation At" time in GORM Customise Join tableGORM Customize Join 表中的“Creation At”时间
【发布时间】:2020-12-23 21:31:48
【问题描述】:

我正在尝试自定义 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,但在任何地方都没有可用的文档。

【问题讨论】:

标签: go go-gorm


【解决方案1】:

使用 Join Table 模型的问题是,如果您想访问模型内​​的字段,则必须显式查询它。

即使用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 v2 (1.20.8)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
相关资源
最近更新 更多