gorm 的关联关系

 主从表的关系之前 一直没有涉及,之前的做法是,作为两次查询,先查询主表,再查询从表,浪费两次交互,后来利用SQL语句手工拼接,得出行数据,逐行解析。

后来发现这个不能发挥json的优势?

json的格式是这样

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

 而行数据模式基本都是这样

[{
      "id": 93,
      "pid": 41,
      "aname": "标书编制",
      "unit": "个",
      "cnt": 1,
      "bonus": 130,
      "remark": "",
      "price": 130
    },
{
      "id": 93,
      "pid": 41,
      "aname": "标书编制",
      "unit": "个",
      "cnt": 1,
      "bonus": 130,
      "remark": "",
      "price": 130
    }
]

 查看gorm的文档,里面有对于关联的说明,这里有比较详细的例子和解释。

但是对于如何关联仍然让人费解,最终在stackoverflow查找,经过实际检验方法如下

//主表结构
type Fi_amount_master struct {
	Id           int32              `gorm:"column:id" json:"id"`
	Month        string             `gorm:"column:month" json:"month"`
	Allbonus     float64            `gorm:"column:allbonus" json:"allbonus"`
	Createdate   time.Time          `gorm:"column:createdate" json:"createdate"`
	Createbyname string             `gorm:"column:createbyname" json:"createbyname"`
	Createbyid   int                `gorm:"column:createbyid" json:"createbyid"`
	Remark       string             `gorm:"column:remark" json:"remark"`
	Auditstatus  string             `gorm:"column:auditstatus" json:"auditstatus"`
	Applydate    time.Time          `gorm:"column:applydate" json:"applydate"`
	Detail       []Fi_amount_detail `gorm:"ForeignKey:DetailRefer"`
}
// 从表结构
type Fi_amount_detail struct {
	Id          int     `gorm:"column:id" json:"id"`
	DetailRefer int     `gorm:"column:pid" json:"pid"`
	Aname       string  `gorm:"column:aname" json:"aname"`
	Unit        string  `gorm:"column:unit" json:"unit"`
	Cnt         int     `gorm:"column:cnt" json:"cnt"`
	Bonus       float64 `gorm:"column:bonus" json:"bonus"`
	Remark      string  `gorm:"column:remark" json:"remark"`
	Price       float64 `gorm:"column:price" json:"price"`
}

// 数据获取

         var master Fi_amount_master
	i.DB.First(&master).Related(&master.Detail, "DetailRefer")

 说明:主表中定义detail 标记 "ForeignKey:DetailRefer"`,在明细表结构中指定 DetailRefer 同时定义数据表中真实的列名`gorm:"column:pid" json:"pid"`

这样在查询master 利用,Related指定关联列名 DetailRefer

 

posted @ 2018-01-17 21:20  mybuilder  阅读(5028)  评论(1编辑  收藏  举报