Sql 从左连接的结果创建嵌套结构-您将如何改进我的方法?
我从左连接的结果中创建嵌套结构-您如何改进我的代码/使其更具习惯性 使用Scan会导致nil指针值出现问题,我希望避免在结构中使用指针纯粹作为左连接的解决方案 我可以使用reflect包而不是手动将列映射到结构吗Sql 从左连接的结果创建嵌套结构-您将如何改进我的方法?,sql,go,sqlx,Sql,Go,Sqlx,我从左连接的结果中创建嵌套结构-您如何改进我的代码/使其更具习惯性 使用Scan会导致nil指针值出现问题,我希望避免在结构中使用指针纯粹作为左连接的解决方案 我可以使用reflect包而不是手动将列映射到结构吗 rows, err := db.Queryx(`SELECT category.id, category.parentId, category.name, category.createdAt, category.updatedAt, item.id, item.categoryId,
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)
}
}