我从 LEFT JOIN 的结果创建嵌套结构 - 你将如何改进我的代码/使其更惯用?
使用 Scan 会导致 nil 指针值出现问题,我想避免在结构中使用指针纯粹作为 LEFT JOIN 的解决方案。
我可以使用反射包而不是手动将列映射到结构吗?
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)
}
}