duanjuda5789 2016-12-08 12:55
浏览 497

Golang Gorm预装

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 0xc042187e40 0xc042187d90 0xc0422cd4a0 0 {0xc042225130} false map[] map[] false}

Thanks in advance for help

  • 写回答

2条回答 默认 最新

  • dongmi4035 2016-12-08 16:20
    关注

    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:"column:record_id" gorm:"primary_key" json:"record_id"`
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?