doucheng4660 2019-02-10 11:12
浏览 12

根据左联接的结果创建嵌套结构-您将如何改进我的方法?

Im creating nested structs from the results of a LEFT JOIN - how would you improve my code / make it more idiomatic?

Using Scan causes issues with nil pointer values and I'd like to avoid using pointers within the structs purely as a solution to the LEFT JOIN.

Could I use the reflect package instead of manually mapping the columns to the structs?

rows, err := db.Queryx(`SELECT
category.id, category.parentId, category.name, category.createdAt, category.updatedAt,
item.id, item.categoryId, item.name, item.createdAt, item.updatedAt
FROM category
LEFT JOIN item ON item.categoryId=category.id
ORDER BY category.id ASC`)
if err != nil {
    return nil, errors.Wrap(err, "Failed to exec category select with items")
}
results := []*CategoryWithItems{}
var prevID int64
var c *CategoryWithItems
for rows.Next() {
    row, err := rows.SliceScan()
    if err != nil {
        return nil, errors.Wrap(err, "Failed to execute SliceScan")
    }
    categoryID := row[0].(int64)
    if prevID == 0 || categoryID != prevID {
        c = &CategoryWithItems{
            Category:Category{
                ID:        categoryID,
                ParentID:  row[1].(int64),
                Name:      string(row[2].([]uint8)),
                CreatedAt: row[3].(time.Time),
                UpdatedAt: row[4].(time.Time),
            },
            Items: []*Item{},
        }
        results = append(results, c)
        prevID = categoryID
    }
    if row[5] != nil {
        i := &Item{
            ID:         row[5].(int64),
            CategoryID: row[6].(int64),
            Name:       string(row[7].([]uint8)),
            CreatedAt:  row[8].(time.Time),
            UpdatedAt:  row[9].(time.Time),
        }
        c.Items = append(c.Items, i)
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 linux驱动,linux应用,多线程
    • ¥20 我要一个分身加定位两个功能的安卓app
    • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
    • ¥15 IAR程序莫名变量多重定义
    • ¥15 (标签-UDP|关键词-client)
    • ¥15 关于库卡officelite无法与虚拟机通讯的问题
    • ¥15 目标检测项目无法读取视频
    • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
    • ¥100 求采集电商背景音乐的方法
    • ¥15 数学建模竞赛求指导帮助