鉴于以下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),但找不到支持我正在寻找的功能的功能。
答案 0 :(得分:0)
假设您有3个表/模型Receipt
,Product
和LineItem
,则可以在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)
}