【问题标题】:Golang gorm preloadingGolang gorm 预加载
【发布时间】:2017-04-23 17:30:42
【问题描述】:

我正在用 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"`
    // ...
}

我想查询数据库并通过附件

获取职位
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=error msg="faked up query" msg=&{0xc04200aca0 can't preload field Attachments for models.Positions 6 0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130} false map[] map[] false}

提前感谢您的帮助

【问题讨论】:

    标签: go foreign-keys preload go-gorm


    【解决方案1】:

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

    在这种情况下,对于“has_many”关联,您应该同时指定外键和关联外键。

    在您的示例中,关联外键是 Position.Sys_id 列,而 Attachment.RecordId 引用它。

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

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

    【讨论】:

      【解决方案2】:

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

      W3 学校:

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

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

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多