Populate slice of objects together with referenced objects

时间:2017-08-04 13:03:00

标签: go go-gorm

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
         }
     }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要在获取订单时急切地加载CurrentState。

在这种情况下,我建议您在http://jinzhu.me/gorm/crud.html#preloading-eager-loading

查看Preload-API