transmet/categories/categories.go

47 lines
1.1 KiB
Go
Raw Normal View History

2015-05-12 05:06:28 +00:00
package categories
import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)
type Category struct {
Id int
Name string
Parent sql.NullInt64
Children []*Category
}
var CategoriesTree []*Category
var CategoriesFlat map[int]*Category
// Cavet: slight cheat. All parents must have Category_id < their children.
func LoadCategories(db *sql.DB) {
CategoriesTree = []*Category{}
CategoriesFlat = make(map[int]*Category)
rows, err := db.Query("select categories.id, categories.name, categories.parent_id from categories order by id,Categories.parent_id desc")
if err != nil {
fmt.Println("DB Error loading Categories:", err)
return
}
for rows.Next() {
category := &Category{Children: []*Category{}}
err = rows.Scan(&category.Id, &category.Name, &category.Parent)
if err != nil {
fmt.Println("Categories DB Error: ", err)
}
CategoriesFlat[category.Id] = category
if category.Parent.Valid {
pid := int(category.Parent.Int64)
CategoriesFlat[pid].Children = append(CategoriesFlat[pid].Children, category)
} else {
CategoriesTree = append(CategoriesTree, category)
}
}
}