Imagine I have 2 structs:
type Order struct {
ID int64 `gorm:"primary_key"`
CurrentStateID int64
CurrentState *OrderState
}
type OrderState struct {
ID int64
.... // other fields
}
Now I want to make a search given a slice of orderIDs
and have a slice of Order
with filled CurrentState
fields.
My current solution is really ugly as I firstly fetch all orders without states, then arrange state ids into a slice and make a search by them. After that, I iterate in a for loop over orders and match orders and states together. Like
var (
states []*State
orders []*Orders
)
//searches are done here
for _, order := range orders {
for _, state := range states {
if order.CurrentStateID == state.ID {
order.CurrentState = state
break
}
}
}
答案 0 :(得分:0)
如果我理解正确,您需要在获取订单时急切地加载CurrentState。
在这种情况下,我建议您在http://jinzhu.me/gorm/crud.html#preloading-eager-loading
查看Preload-API