如何在 Golang 中使用另一个数组的 ID 填充一个数组
How to fill an array using another array's IDs in Golang
所以我想从 comms 中的 ID 获取所有 commPlans,但由于某种原因我只得到一个对象(这是 comms 中的第一个 ID)。
这是我的代码:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
var commPlans []models.CommPlan
for _, comm := range comms {
commPlans = models.GetCommPlans(comm.CommPlanID)
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
您需要 append
来自 GetCommPlans
的结果到 commPlans
切片,现在您正在覆盖之前返回的任何结果。
要么:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
// a slice of slices
var commPlans [][]models.CommPlan
for _, comm := range comms {
commPlans = append(commPlans, models.GetCommPlans(comm.CommPlanID))
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
或者:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
var commPlans []models.CommPlan
for _, comm := range comms {
commPlans = append(commPlans, models.GetCommPlans(comm.CommPlanID)...)
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
所以我想从 comms 中的 ID 获取所有 commPlans,但由于某种原因我只得到一个对象(这是 comms 中的第一个 ID)。 这是我的代码:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
var commPlans []models.CommPlan
for _, comm := range comms {
commPlans = models.GetCommPlans(comm.CommPlanID)
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
您需要 append
来自 GetCommPlans
的结果到 commPlans
切片,现在您正在覆盖之前返回的任何结果。
要么:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
// a slice of slices
var commPlans [][]models.CommPlan
for _, comm := range comms {
commPlans = append(commPlans, models.GetCommPlans(comm.CommPlanID))
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
或者:
comms := models.GetComms(CommID)
if comms == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}
var commPlans []models.CommPlan
for _, comm := range comms {
commPlans = append(commPlans, models.GetCommPlans(comm.CommPlanID)...)
}
if commPlans == nil {
componentsJson.WriteError(ctx, componentsError.ERROR_PARAMETERS_INVALID)
return
}