load tags into tree, display them as tree with depth 2, ordered

This commit is contained in:
Dan Ballard 2015-05-08 00:07:30 -07:00
parent 605fc93409
commit 9ca8deed23
2 changed files with 23 additions and 24 deletions

View File

@ -4,47 +4,43 @@ import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
"strings"
"strconv"
)
type Tag struct {
Id int
Name string
Parent sql.NullInt64
Children []int
Children []*Tag
}
var Tags map[int]*Tag
var Tags []*Tag
func LoadTags(db *sql.DB) {
Tags = make(map[int]*Tag)
rows, err := db.Query("select tags.tag_id, tags.name, tags.parent_id, array_agg(distinct(parent_of.tag_id)) as children from tags left join tags as parent_of on parent_of.parent_id=tags.tag_id group by tags.tag_id")
Tags = []*Tag{}
//rows, err := db.Query("select tags.tag_id, tags.name, tags.parent_id, array_agg(distinct(parent_of.tag_id)) as children from tags left join tags as parent_of on parent_of.parent_id=tags.tag_id group by tags.tag_id")
rows, err := db.Query("select tags.tag_id, tags.name, tags.parent_id from tags order by tag_id,tags.parent_id desc")
if err != nil {
fmt.Println("DB Error loading tags:", err)
return
}
var flatMap map[int]*Tag = make(map[int]*Tag)
for rows.Next() {
tag := &Tag{Children: nil}
tag := &Tag{Children: []*Tag{}}
var children sql.NullString
var tag_id int
err = rows.Scan(&tag_id, &tag.Name, &tag.Parent, &children)
err = rows.Scan(&tag.Id, &tag.Name, &tag.Parent)
if err != nil {
fmt.Println("tags DB Error: ", err)
}
if children.Valid {
var childrenStr = children.String[1 : len(children.String)-1]
if childrenStr != "NULL" {
pids := strings.Split(childrenStr, ",")
for _, spid := range pids {
pid, _ := strconv.Atoi(spid)
tag.Children = append(tag.Children, pid)
}
}
}
Tags[tag_id] = tag
flatMap[tag.Id] = tag
if tag.Parent.Valid {
pid := int(tag.Parent.Int64)
flatMap[pid].Children = append(flatMap[pid].Children, tag)
} else {
Tags = append(Tags, tag)
}
}
}

View File

@ -21,5 +21,8 @@
{{define "option-tag"}}
<option>{{.Name}}</option>
<option value="{{.Id}}">{{if .Parent.Valid}}-{{end}}{{.Name}}</option>
{{range $child := .Children}}
{{template "option-tag" $child}}
{{end}}
{{end}}