reprogl
90 строк · 1.5 Кб
1package repositories2
3import (4"database/sql"5"errors"6
7"xelbot.com/reprogl/models"8)
9
10type CategoryRepository struct {11DB *sql.DB12}
13
14func (cr *CategoryRepository) GetBySlug(slug string) (*models.Category, error) {15query := `16SELECT
17c.id,
18c.name,
19c.url,
20c.tree_left_key,
21c.tree_right_key,
22c.tree_depth
23FROM category AS c
24WHERE (c.url = ?)`
25
26category := &models.Category{}27
28err := cr.DB.QueryRow(query, slug).Scan(29&category.ID,30&category.Name,31&category.Slug,32&category.LeftKey,33&category.RightKey,34&category.Depth)35
36if err != nil {37if errors.Is(err, sql.ErrNoRows) {38return nil, models.RecordNotFound39} else {40return nil, err41}42}43
44return category, nil45}
46
47func (cr *CategoryRepository) GetCategoryTree() (*models.CategoryList, error) {48query := `49SELECT c.id,
50c.name,
51c.url,
52c.tree_depth
53FROM category AS c,
54(SELECT c0.id
55FROM category AS c0,
56category AS c1
57INNER JOIN posts AS p ON c1.id = p.category_id
58WHERE c0.tree_left_key <= c1.tree_left_key
59AND c0.tree_right_key >= c1.tree_right_key
60AND p.hide = 0
61GROUP BY c0.id) AS cnt
62WHERE c.id = cnt.id
63ORDER BY c.tree_left_key`
64
65rows, err := cr.DB.Query(query)66if err != nil {67return nil, err68}69
70defer rows.Close()71
72categories := models.CategoryList{}73
74for rows.Next() {75category := &models.Category{}76err = rows.Scan(77&category.ID,78&category.Name,79&category.Slug,80&category.Depth)81
82if err != nil {83return nil, err84}85
86categories = append(categories, category)87}88
89return &categories, nil90}
91