Golang gorm预加载

huangapple go评论74阅读模式
英文:

Golang gorm preloading

问题

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

我有两个表,positionattachment。每个position可以有多个attachment。这是我的模型:

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

我想查询数据库并获取带有附件的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")
}

这个查询的结果是,我正确地获取了positions,但是attachments为空。

>(无法预加载models.Positions的Attachments字段)
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}

提前感谢您的帮助。

英文:

I'm writing my first app in golang, so sorry for newbie question, but I wasn't able to find the solution for the following problem:

I have two tables, position and attachment. Each position can have multiple attachments. Here is my model:

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

I want to query the db and get positions with attachments

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

Result of this query - I get positions correctly but the attachments are empty.

>(can't preload field Attachments for models.Positions)
level=error msg="faked up query" msg=&{0xc04200aca0 can't preload field Attachments for models.Positions 6 <nil> 0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130} <nil> false map[] map[] false}

Thanks in advance for help

答案1

得分: 4

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

在这种情况下,对于"has_many"关联,你应该同时指定Foreign Key和Association Foreign Key。

在你的示例中,Association Foreign Key是Position.Sys_id列,Attachment.RecordId引用它。

所以只需添加Association foreign key即可修复:

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

英文:

Models in your example have custom primary column names.
So, when only ForeignKey set for "has_many" association, Gorm trying to find Position's column Attachment.RecordId refers to.
By default it uses Position as prefix and Id as column name for this. But neither RecordId column has prefix Position nor Position model has column Id, so it fails.

In such case for "has_many" association you should specify both Foreign Key and Association Foreign Key.

In your example Association Foreign Key is the Position.Sys_id column and Attachment.RecordId refers to it.

So it should be fixed just by adding Association foreign key:

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

答案2

得分: -1

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

W3SCHOOLS:

> 一个表中的外键指向另一个表中的主键。

但是在你的模型中,RecordId不是一个主键。让外键引用一个主键。应该使用以下修复方法:

RecordId int `gorm:&quot;column:record_id&quot; gorm:&quot;primary_key&quot; json:&quot;record_id&quot;`
英文:

Looks like it is not about Go or Gorm but about SQL.

W3SCHOOLS:

> A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

But RecordId is not a primary key in your model. Let the foreign key refer to a primary key. It should be fixed with:

RecordId int `gorm:&quot;column:record_id&quot; gorm:&quot;primary_key&quot; json:&quot;record_id&quot;`

huangapple
  • 本文由 发表于 2016年12月8日 20:55:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/41040046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定