Golang gorm预加载

时间:2016-12-08 12:55:07

标签: go foreign-keys preload go-gorm

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

我有两个表,位置附件。每个职位可以有多个附件。这是我的模特:

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"`
    // ...
}

我想查询数据库并使用附件获取职位

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")
}

此查询的结果 - 我正确获取了位置,但附件是空的。

  

(无法预加载model.Positions的字段附件)       level = error msg ="伪造查询" msg =& {0xc04200aca0无法预加载模型的附件。位置6 0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130} false map [] map [] false}

提前感谢您的帮助

2 个答案:

答案 0 :(得分: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 :(得分:-1)

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

W3Schools的:

  

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

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

RecordId int `gorm:"column:record_id" gorm:"primary_key" json:"record_id"`
相关问题