使用Gorm将值从一列映射到单独表中的另一列

时间:2018-09-13 23:46:22

标签: go go-gorm

鉴于以下Option Explicit Sub LoopThroughDirectory() Dim myFile As String, filepath As String Dim wbc As Long, ws As Worksheet, wb As Workbook wbc = 0 filepath = "C:\Test\" 'Application.ScreenUpdating = False 'only try to open workbooks myFile = Dir(filepath & "*.xls*") 'Opens workbooks located C:\Test\ in order Do While Len(myFile) > 0 'make sure myFile isn't ThisWorkbook If Split(myFile & ".", ".")(0) <> Split(ThisWorkbook.Name & ".", ".")(0) Then Set wb = Workbooks.Open(Filename:=filepath & myFile, ReadOnly:=True) 'Application.DisplayAlerts = False 'check if there is a Results worksheet On Error Resume Next Set ws = wb.Worksheets("Results") On Error GoTo 0 If Not ws Is Nothing Then 'transfer cells B2 & C2 from the results worksheet With ws.Range("B2:C2") ThisWorkbook.Worksheets("x").Range("A1").Offset(wbc, 0).Resize(.Rows.Count, .Columns.Count) = .Value End With End If 'Close wb most recently opened wb.Close SaveChanges:=False wbc = wbc + 1 If wbc > 1000 Then Exit Do End If Set ws = Nothing myFile = Dir Loop ActiveWorkbook.Save 'Application.ScreenUpdating = True End Sub 关系(一个one-to-many有许多Receipt),我想映射LineItem表中的Price字段进入Receipt表的Price字段(对于LineItem中的每个LineItem)。

接收模式

Product

}

LineItem架构

type Product struct {
ID             uint       `json:"id"`
TotalPrice     float64    `json:"total"`
LineItems      []LineItem `json:"lineItems"`

我目前正在使用gorm(一种用于Go的ORM),但找不到支持我正在寻找的功能的功能。

1 个答案:

答案 0 :(得分:0)

假设您有3个表/模型ReceiptProductLineItem,则可以在Product模型中添加引用LineItem的字段,例如所以:

type Receipt struct {
    ID             uint       `json:"id"`
    TotalPrice     float64    `json:"total"`
    LineItems      []LineItem `json:"lineItems"`
}

type Product struct {
    ID          uint    `json:"id"`
    Price       float64 `json:"price"`
}

type LineItem struct {
    ID          uint     `json:"id"`
    ProductID   uint     `json:"productID"`
    Product     *Product `json:"product"`
}

然后,您可以使用gorm的Preload功能在填充Receipt字段以及每个LineItems中的Product字段的同时查询LineItem

db.Preload("LineItems").Preload("LineItems.Product").Find(&receipt)

通过这种方式,您将可以通过LineItem字段访问每个Product中的价格信息:

for _, li in receipt.LineItems {
    fmt.Println(li.Product.Price)
}