首页 文章

Golang gorm预加载

提问于
浏览
0

我正在golang编写我的第一个应用程序,很抱歉新手问题,但我无法找到以下问题的解决方案:

我有两个表, positionattachment . 每个职位可以有多个附件 . 这是我的模型:

type Positions struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id,omitempty"`
    Name string `gorm:"size:120" gorm:"column:name" json:"name,omitempty"`
    OpenPositions int `gorm:"column:open_positions" json:"open_positions,omitempty"`
    ContactList string `gorm:"size:1000" gorm:"column:contact_list" json:"contact_list,omitempty"`
    Attachments []Attachment `gorm:"ForeignKey:RecordId"`
}

type Attachment struct {
    Sys_id     int `gorm:"AUTO_INCREMENT" gorm:"column:sys_id" json:"sys_id"`
    Name string `gorm:"size:255" gorm:"column: name" json:"name"`
    File string `gorm:"size:255" gorm:"column:file" json:"file"`
    RecordId int `gorm:"column:record_id" json:"record_id"`
    Table string `gorm:"size:255" gorm:"column:table" json:"table"`
    // ...
}

我想查询db并使用 attachments 获取 positions

positions2 := []models.Positions{}
err := db.Where("open_positions > ?", 0).Preload("Attachments", "`table` = ?", "user_position").Find(&positions2)
if err != nil {
    log.WithFields(log.Fields{
        "type": "queryerr",
        "msg": err,
    }).Error("faked up query")
}

此查询的结果 - 我正确获取位置但附件为空 .

(无法预加载模型的字段附件 . 位置)level =错误msg =“faked up query”msg =&{0xc04200aca0无法预加载字段模型的附件 . 位置6 0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130} false map [] map [] false}

在此先感谢您的帮助

2 回答

  • 0

    示例中的模型具有自定义主列名称 . 因此,当只有ForeignKey设置为“has_many”关联时,Gorm试图找到Position的列Attachment.RecordId引用 . 默认情况下,它使用Position作为前缀,Id作为列名称 . 但是RecordId列都没有前缀Position和Position模型都有列Id,所以它失败了 .

    在“has_many”关联的情况下,您应指定外键和关联外键 .

    在您的示例中,Association Foreign Key是Position.Sys_id列,Attachment.RecordId是指它 .

    所以它应该通过添加Association外键来修复:

    Attachments   []Attachment `gorm:"ForeignKey:RecordId;AssociationForeignKey:sys_id"`
    
  • -1

    看起来它不是关于Go或Gorm而是关于SQL .

    W3Schools的:

    一个表中的FOREIGN KEY指向另一个表中的PRIMARY KEY .

    但是 RecordId 不是模型中的主键 . 让外键引用主键 . 应该修复:

    RecordId int `gorm:"column:record_id" gorm:"primary_key" json:"record_id"`
    

相关问题