如何在 PostgreSQL 中使用 GORM Raw 选择数组?

问题描述 投票:0回答:1

我在我的应用程序日志中收到此错误:

[error] unsupported data type: &[] 

我想做的是使用

SELECT
对多对多数据运行
json_agg()
查询,其中我正在使用的结构中的数据类型是
[]string

这是

GetArticleById
结构

type GetArticleByID struct{
    ID              string          `json:"article_id" gorm:"column:article_id"`
    Title           string          `json:"title"`
    Content         string          `json:"content"`
    CreatedAt       time.Time       `json:"created_at"`
    Author          string          `json:"author"`
    Category        string          `json:"category"`
    SubCategory     string          `json:"sub_category"`
    Keywords        []string        `json:"keywords"`
    Unit            string          `json:"unit"`
}

这是查询执行

query := `SELECT 
                a.article_id, a.title, a.created_at, a.content, u.name AS author, c.name AS category, sc.name AS sub_category,
                json_agg(k.name) AS keywords, unit.name AS unit
            FROM 
                articles a
                LEFT JOIN users u ON a.user_id = u.user_id
                LEFT JOIN categories c ON a.category_id = c.categ_id
                LEFT JOIN sub_categories sc ON a.sub_category_id = sc.sub_categ_id
                LEFT JOIN article_keywords ak ON a.article_id = ak.article_refer_id
                LEFT JOIN keywords k ON ak.keyword_refer_id = k.keyword_id
                LEFT JOIN units unit ON a.unit_id = unit.unit_id
            WHERE 
                a.article_id = ? AND
                a.is_posted = true
            GROUP BY 
                a.article_id, u.name, c.name, sc.name, unit.name`

    err := db.Raw(query, id).Scan(&article).Error

我想使用Raw SQL而不是ORM,因为这是一个项目,我想测试一下Raw SQL和ORM的比较。

database postgresql go struct go-gorm
1个回答
0
投票

通过在

GetArticleById
结构上为
Keywords

添加 gorm 序列化器标签来解决此问题
type GetArticleByID struct {
    ID          string    `json:"article_id" gorm:"column:article_id"`
    Title       string    `json:"title"`
    Content     string    `json:"content"`
    CreatedAt   time.Time `json:"created_at"`
    Author      string    `json:"author"`
    Category    string    `json:"category"`
    SubCategory string    `json:"sub_category"`
    Keywords    []string  `json:"keywords" gorm:"serializer:json"`
    Unit        string    `json:"unit"`
}
© www.soinside.com 2019 - 2024. All rights reserved.