load tags into tree, display them as tree with depth 2, ordered
This commit is contained in:
parent
605fc93409
commit
9ca8deed23
40
tags/tags.go
40
tags/tags.go
|
@ -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
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
tag := &Tag{Children: nil}
|
||||
var flatMap map[int]*Tag = make(map[int]*Tag)
|
||||
|
||||
var children sql.NullString
|
||||
var tag_id int
|
||||
err = rows.Scan(&tag_id, &tag.Name, &tag.Parent, &children)
|
||||
for rows.Next() {
|
||||
tag := &Tag{Children: []*Tag{}}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
flatMap[tag.Id] = tag
|
||||
|
||||
Tags[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)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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}}
|
Loading…
Reference in New Issue