【问题标题】:using Preload and Join in gorm在 gorm 中使用 Preload 和 Join
【发布时间】:2021-08-12 01:37:16
【问题描述】:

假设我有这 3 个结构

type Question struct {
    gorm.Model
    Id            *uint64        `json:"id" gorm:"column=id;primaryKey;autoIncrement"`
    Name          string         `json:"name" gorm:"unique"`
    SkillId       *uint64        `json:"skill_id"`
    TestQuestions []TestQuestion `json:"test_questions"`

}
type Skill struct {
    gorm.Model
    SkillName     string `json:"skill_name"`
    Question []Question
}
type TestQuestion struct {
    gorm.Model
    QuestionId uint64 `json:"question_id"`
    TestId     uint64 `json:"test_id"`
}

我想选择所有问题,对于每个问题,我想选择该问题的技能名称而不是技能 ID,并且我想预加载 TestQuestion 我试图让这个结构来存储我的结果

type struct QuestionResponse(
    SkillName    string
    Name         string    `json:"name"`
    TestQuestions TestQuestion `json:"test_questions"`
}

我试过这个查询

db.Table("questions").Preload("TestQuestions").
                Joins("inner join skills on questions.skill_id = skills.id").
        Select("questions.name,skills.skill_name, questions.difficulty, questions.max_points, questions.type, questions.expected_time, questions.question_text,questions.file_read_me").
        Find(&question)

但我收到此错误“为 struct github.com ...../models.QuestionResponse 的字段 TestQuestions 找到无效字段:为关系定义有效外键或实现 Valuer/Scanner 接口” 有什么解决办法吗?

【问题讨论】:

  • 在关系数据库中,列不能是数组,而是在对象数据库中(mongo、elasticsaerch);技能表应该是这样的: type Skill struct { gorm.Model SkillName string json:"skill_name" QuestionId int // 表问题中的问题 ID }
  • 一个问题有一个技能,一个技能在很多问题中,这就是为什么他需要以他的方式定义结构

标签: mysql go go-gorm


【解决方案1】:

首先我建议你在你的结构中使用 gorm 标签,第二个 gorm.Model 已经给了我们一些基本字段,比如 ID 作为主键等 (https://gorm.io/docs/models.html#gorm-Model) 但这是节省一些时间的结构:

// gorm.Model definition
type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}

我不明白你想用你的结构做什么,所以我建议你看看这个:Gorm relationship error: need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface,并更多地考虑你的数据库的关系。

基本:(感谢https://stackoverflow.com/users/415628/ezequiel-muns

  • foreignKey 应该命名连接到外部实体的模型本地键字段。
  • 引用应命名外部实体的主键或唯一键。

请记住,.Preload("some stuff"), 将基本执行选择 (*),以满足数据库中结构的 Struct(例如来自用户的订单),因此有时更好您想要嵌入的字段并具有该选择的唯一结构,而不是“适合所有”结构。 Gorm 有一些像 Omit() 这样的函数来省略插入或更新中的字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多