GORM - “`”附近存在语法错误,但使用字符串文字的查询中没有反引号

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

我将此代码递归到类别结构中:

我使用了这个查询:

        err = DB.Exec(`
            WITH RECURSIVE CategoryCTE AS (
                SELECT ID, Title, Parent_id, Description, Shortcut, Icon, Public, 0 AS Depth
                FROM categories
                WHERE id IN (?)  -- Start from the specified base category IDs
            
                UNION ALL
            
                SELECT c.ID, c.Title, c.Parent_id, c.Description, c.Shortcut, c.Icon, c.Public, cte.Depth + 1 as Depth
                FROM categories c
                INNER JOIN CategoryCTE cte ON c.parent_id = cte.id
                HAVING Depth < ?  -- Limit to the specified Depth
            )
            SELECT * FROM CategoryCTE;`,
            catIDs,
            depth,
        ).Scan(&cats).Error
    var cats []MinifiedCategory

    if depth > 1 {
        // Convert catIDs to string for IN clause
        var catIDstring []string
        for _, id := range catIDs {
            catIDstring = append(catIDstring, strconv.Itoa(int(id)))
        }

        // Recursive CTE query to get subcategories, scan result to MinifiedCategory
        var query string = fmt.Sprintf(`
            WITH RECURSIVE CategoryCTE AS (
                SELECT ID, Title, Parent_id, Description, Shortcut, Icon, Public, 0 AS Depth
                FROM categories
                WHERE id IN (%s)  -- Start from the specified base category IDs
            
                UNION ALL
            
                SELECT c.ID, c.Title, c.Parent_id, c.Description, c.Shortcut, c.Icon, c.Public, cte.Depth + 1 as Depth
                FROM categories c
                INNER JOIN CategoryCTE cte ON c.parent_id = cte.id
                HAVING Depth < %d  -- Limit to the specified Depth
            )
            SELECT * FROM CategoryCTE;
        `, strings.Join(catIDstring, ","), depth)

        // Execute query and scan result to MinifiedCategory
        err = DB.Exec(query).Scan(&cats).Error

我试图保持它的可读性,所以我将它保留在字符串文字中。我使用带有参数的 exec 。现在我正在尝试这个。没有任何效果!

每次我得到

Error #01: Error 1064 (42000): You have an error in your SQL syntax;...near '(backtick)' at line 1

我尝试打印并导出到文件中,亲眼看到查询中根本没有反引号!但它总是因这个错误而失败。

 Error #01: Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '`' at line 1

如何在 GORM 查询中使用反引号但又不会陷入困境?或者我做错了什么? 谢谢。


当使用 DB.Raw 而不是 DB.Exec 时,它可以工作。不知道为什么。谢谢

go mariadb go-gorm string-literals
1个回答
0
投票

用双引号交换反引号

s := fmt.Sprintf("%s is %d years old.\n", name, age)

https://pkg.go.dev/fmt#example-Sprintf

此外,我会按照 GORM 文档来构建查询

db.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})

https://gorm.io/docs/sql_builder.html#Raw-SQL

© www.soinside.com 2019 - 2024. All rights reserved.