SQL:
SELECT p.project_id, p.name,
COALESCE(NULLIF(json_agg(a.*)::TEXT, '[null]'), '[]')::JSON AS apps
FROM project p LEFT JOIN app a USING (project_id)
WHERE p.user_id=19
GROUP BY p.project_id, p.name ORDER BY project_id
戈朗
type Project struct {
ID int64 `db:"project_id, primarykey, autoincrement" json:"id"`
UserID int64 `db:"user_id" json:"user_id"`
Name string `db:"name" json:"name"`
Status int `db:"status" json:"status"`
UpdatedAt int64 `db:"updated_at" json:"updated_at"`
CreatedAt int64 `db:"created_at" json:"created_at"`
Apps json.RawMessage `json:"apps"`
}
func GetProjects(userID int64, page string) []Project {
var projects []Project
var err error
_, err = db.GetDB().Select(&projects, "SELECT p.project_id, p.name, COALESCE(NULLIF(json_agg(a.*)::TEXT, '[null]'), '[]')::JSON AS apps FROM project p LEFT JOIN app a USING (project_id) WHERE p.user_id=$1 GROUP BY p.project_id, p.name ORDER BY project_id LIMIT 10 OFFSET $2", userID, page)
fmt.Println("err", err)
return projects
}
并使用以下方法返回结果:c.JSON(200, gin.H{"data": projects})
如果只有一个项目,它可以工作
但如果有多个项目,则会出现以下错误:
错误:json: error calling MarshalJSON for type json.RawMessage: invalid character '"' after top-level value
有什么建议么?
PS:我是Golang的新手