package categories import ( "database/sql" _ "github.com/lib/pq" "fmt" "strings" ) 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 coalesce(parent_id, id), parent_id is not null") if err != nil { fmt.Println("DB Error loading Categories:", err) return } defer rows.Close() 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) } } } // get the number of parents a category has func (category *Category) Depth() int { depth := 0 current := category for current.Parent.Valid { current = CategoriesFlat[int(current.Parent.Int64)] depth ++ } return depth } // Helper function for templates (add form select list) func (category *Category) ToString() string { return strings.Repeat("- ", category.Depth()) + category.Name }