如何合并相关数据

时间:2019-03-13 21:01:01

标签: json go

我需要代码组织方面的理论/实践帮助。

我在PostgreSQL数据库中有这样的表。该表显示了组织之间的关系。

| ORGANIZATION_ID | ORGANIZATION_NAME | PARENT_ORGANIZATION_ID | ORGANIZATION_RANG | TREE_ORGANIZATION_ID | TREE_ORGANIZATION_ NAME |
|-----------------|-------------------|------------------------|-------------------|----------------------|-------------------------|
| 1               | Google            |                        | 1                 | \1                   | \Google                 |
| 2               | Nest              | 1                      | 2                 | \1\2                 | \Google\Nest            |
| 3               | Verily            | 1                      | 2                 | \1\3                 | \Google\Verily          |
| 4               | Calico            |                        | 1                 | \4                   | \Calico                 |
| 5               | ATAP              | 4                      | 2                 | \4\5                 | \Calico\ATAP            |

在我的Go应用程序中,我为此表创建struct,然后进行SQL查询。

type Organization struct {
    ID int `json:"organization_id"`
    Name string `json:"organization_name"`
    Rang int `json:"organization_rang"`
    Children []Organization `json:"children"`
}

var GetOrganizations = func(responseWriter http.ResponseWriter, request *http.Request) {
    rows,err := db.Query("select * from ORG")
    if err != nil {
        fmt.Println(err)
        return
    }

    defer rows.Close()

    var organizations []Organization

    for rows.Next() {
        var organization Organization

        err = rows.Scan(&organization.ID, &organization.Name, &organization.Rang)
        if err != nil {
            fmt.Println(err)
            return
        }

        organizations = append(organizations, organization)
    }

    utils.Response(responseWriter, http.StatusOK, organizations)
}

我需要做出这样的回应。您建议在我当前的代码中进行什么重组?

[
    {
        "organization_id": 1,
        "organization_name": "Google",
        "organization_rang": 1,
        "children": [
            {
                "organization_id": 2,
                "organization_name": "Nest",
                "organization_rang": 2,
                "children": null
            },
            {
                "organization_id": 3,
                "organization_name": "Verily",
                "organization_rang": 2,
                "children": null
            }
        ]
    },
    {
        "organization_id": 4,
        "organization_name": "Calico",
        "organization_rang": 1,
        "children": [
            {
                "organization_id": 2,
                "organization_name": "Nest",
                "organization_rang": 2,
                "children": null
            }
        ]
    }
]

编辑

例如,

@antham我添加了名为Telsa的新记录。如您所见,它的父对象是Nest对象。

| ORGANIZATION_ID | ORGANIZATION_NAME | PARENT_ORGANIZATION_ID | ORGANIZATION_RANG | TREE_ORGANIZATION_ID | TREE_ORGANIZATION_ NAME |
|-----------------|-------------------|------------------------|-------------------|----------------------|-------------------------|
| 1               | Google            |                        | 1                 | \1                   | \Google                 |
| 2               | Nest              | 1                      | 2                 | \1\2                 | \Google\Nest            |
| 3               | Verily            | 1                      | 2                 | \1\3                 | \Google\Verily          |
| 4               | Calico            |                        | 1                 | \4                   | \Calico                 |
| 5               | ATAP              | 4                      | 2                 | \4\5                 | \Calico\ATAP            |
| 6               | Tesla             | 2                      | 3                 | \1\2\6               | \Google\Nest\Tesla      |

您的代码结果:

[
    {
        "organization_id": 1,
        "organization_name": "Google",
        "organization_rang": 1,
        "children": [
            {
                "organization_id": 3,
                "organization_name": "Verily",
                "organization_rang": 2,
                "children": null
            },
            {
                "organization_id": 2,
                "organization_name": "Nest",
                "organization_rang": 2,
                "children": [
                    {
                        "organization_id": 6,
                        "organization_name": "Tesla",
                        "organization_rang": 3,
                        "children": null
                    }
                ]
            }
        ]
    },
    {
        "organization_id": 2,
        "organization_name": "Nest",
        "organization_rang": 2,
        "children": [
            {
                "organization_id": 6,
                "organization_name": "Tesla",
                "organization_rang": 3,
                "children": null
            }
        ]
    },
    {
        "organization_id": 4,
        "organization_name": "Calico",
        "organization_rang": 1,
        "children": [
            {
                "organization_id": 5,
                "organization_name": "ATAP",
                "organization_rang": 2,
                "children": null
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您想做什么,那么这里有一个未优化的示例,它是使用sqlite完成的,但它与postgres相同:

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "sort"

    _ "github.com/mattn/go-sqlite3"
)

type Organization struct {
    ID       int             `json:"organization_id"`
    Name     string          `json:"organization_name"`
    Rang     int             `json:"organization_rang"`
    Children []*Organization `json:"children"`
}

func main() {
    db, err := sql.Open("sqlite3", "./database")
    if err != nil {
        log.Fatal(err)
    }

    defer db.Close()

    rows, err := db.Query("select ORGANIZATION_ID,ORGANIZATION_NAME,ORGANIZATION_RANG,PARENT_ORGANIZATION_ID from ORG")
    if err != nil {
        log.Fatal(err)
    }

    defer rows.Close()

    orgs := map[int]*Organization{}

    for rows.Next() {
        organization := &Organization{}
        var parentID sql.NullInt64

        if err = rows.Scan(&organization.ID, &organization.Name, &organization.Rang, &parentID); err != nil {
            log.Fatal(err)
        }

        if parentID.Valid {
            if parentOrg, ok := orgs[int(parentID.Int64)]; ok {
                parentOrg.Children = append(parentOrg.Children, organization)
            } else {
                orgs[int(parentID.Int64)] = &Organization{ID: int(parentID.Int64)}
                orgs[int(parentID.Int64)].Children = append(orgs[int(parentID.Int64)].Children, organization)
            }
        }

        if _, ok := orgs[organization.ID]; ok {
            orgs[organization.ID].Name = organization.Name
            orgs[organization.ID].Rang = organization.Rang
            continue
        }

        orgs[organization.ID] = organization
    }

    IDs := []int{}
    for k := range orgs {
        IDs = append(IDs, k)
    }
    sort.Ints(IDs)

    organizations := []Organization{}
    for _, ID := range IDs {
        if len(orgs[ID].Children) > 0 && orgs[ID].Rang == 1 {
            organizations = append(organizations, *orgs[ID])
        }
    }

    content, err := json.MarshalIndent(organizations, "", "  ")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(content))
}

我明白了:

[
  {
    "organization_id": 1,
    "organization_name": "Google",
    "organization_rang": 1,
    "children": [
      {
        "organization_id": 2,
        "organization_name": "Nest",
        "organization_rang": 2,
        "children": null
      },
      {
        "organization_id": 3,
        "organization_name": "Verily",
        "organization_rang": 2,
        "children": null
      }
    ]
  },
  {
    "organization_id": 4,
    "organization_name": "Calico",
    "organization_rang": 1,
    "children": [
      {
        "organization_id": 5,
        "organization_name": "ATAP",
        "organization_rang": 2,
        "children": null
      }
    ]
  }
]