gpt4 book ai didi

go - sqlx 无法对嵌套结构使用结构扫描

转载 作者:行者123 更新时间:2023-12-05 08:06:37 29 4
gpt4 key购买 nike

我有不同类型的 REST API,它们有一些共同点:

  1. 所有类型都有Id
  2. 所有类型都有类型
  3. 所有类型都有属性,但属性不同

因为我不想有大量不必要的类型,所以我提出了一种类型格式,但它似乎不能被 sqlx 扫描。

type Pool struct {
Id *string `json:"id" db:"pool_id"`
Type *string `json:"type"`
Attributes struct {
Name *string `json:"name" db:"name"`
Description *string `json:"description" db:"description"`
} `json:"attributes"`
}

type User struct {
Id *string `json:"id" db:"user_id"`
Type *string `json:"type"`
Attributes struct {
FirstName *string `json:"first_name" db:"first_name"`
LastName *string `json:"last_name" db:"last_name"`
} `json:"attributes"`
}

尝试将 SQL 结果加载到变量中时出现错误:missing destination name name in *main.Pool

package main

import (
_ "github.com/jmoiron/sqlx"
)

func selectOne() interface{} {
pa := Pool{}
err := dbx.Get(&pa, "SELECT * FROM pools LIMIT 1")
if err != nil {
panic(err)
}

return pa
}

由于名称存在,我不明白为什么这不起作用。非常感谢任何解决此问题的建议!

最佳答案

package main

import (
_ "github.com/jmoiron/sqlx"
)


func selectOne() interface{} {
pa := Pool{}
err := dbx.Get(&pa, `SELECT p.id, p.type, a.name AS "attributes.name" FROM pools p left join attributes a on a.p LIMIT 1`)
if err != nil {
panic(err)
}
return pa
}

关于go - sqlx 无法对嵌套结构使用结构扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60010162/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com