Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
&引用;“在”处创建;GORM中的时间自定义联接表_Go_Go Gorm_Gorm Mysql - Fatal编程技术网

&引用;“在”处创建;GORM中的时间自定义联接表

&引用;“在”处创建;GORM中的时间自定义联接表,go,go-gorm,gorm-mysql,Go,Go Gorm,Gorm Mysql,我正在尝试自定义多个表联接。我有两个表,我想从中获取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

我正在尝试自定义多个表联接。我有两个表,我想从中获取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方法,但在较新版本中它已被弃用。有一个SetJointTableHandler,但任何地方都没有可供使用的文档。

使用联接表模型的方法是,如果要访问模型内的字段,必须显式查询它

这就是使用
db.Model(&User{ID:1}).Association(“Challenges”).Find(&Challenges)
db.Preload(“Challenges”).Find(&users)
等只会给你相关结构的集合,在这些集合中没有放置额外字段的位置

为此,您可以:

加入:=[]用户挑战{}
db.Where(“user\u id=?”,user.id).Find(&joins)
//现在联接包含联接表中与user.ID有关的所有记录,
//您可以访问联接[i]。例如,CreatedAt。
如果您还想用它检索挑战,可以修改join结构,将其与挑战的BelongsTo关系集成,并预加载它:

类型UserChallenges struct{
UserID int`gorm:“primaryKey”`
ChallengeID int`gorm:“primaryKey”`
挑战
时间,时间
}
加入:=[]用户挑战{}
db.Where(“user_id=?”,user.id).Joins(“Challenge”).Find(&Joins)
//现在加入[i]。已填充挑战

使用联接表模型的好处是,如果要访问模型内的字段,必须显式查询它

这就是使用
db.Model(&User{ID:1}).Association(“Challenges”).Find(&Challenges)
db.Preload(“Challenges”).Find(&users)
等只会给你相关结构的集合,在这些集合中没有放置额外字段的位置

为此,您可以:

加入:=[]用户挑战{}
db.Where(“user\u id=?”,user.id).Find(&joins)
//现在联接包含联接表中与user.ID有关的所有记录,
//您可以访问联接[i]。例如,CreatedAt。
如果您还想用它检索挑战,可以修改join结构,将其与挑战的BelongsTo关系集成,并预加载它:

类型UserChallenges struct{
UserID int`gorm:“primaryKey”`
ChallengeID int`gorm:“primaryKey”`
挑战
时间,时间
}
加入:=[]用户挑战{}
db.Where(“user_id=?”,user.id).Joins(“Challenge”).Find(&Joins)
//现在加入[i]。已填充挑战

SetJoinTableHandler似乎来自早期版本:未显示当前代码中的名称。SetJoinTableHandler似乎来自早期版本:未显示当前代码中的名称。这适用于gorm v2(1.20.8)这适用于gorm v2(1.20.8)