sql 查询一对多数据,并赋值给结构体

最简单的办法:使用copier库

copier.Copy(&A, &B)  // 将B切片赋值给A切片

参考这个博客:https://darjun.github.io/2020/03/13/godailylib/copier/

 

使用for循环方法:

我使用sqlx查询数据库数据,查询结果如下:

我想通过内嵌切片结构体获取查询数据 并返如下json格式

 

type User struct {
    ID       int    `db:"id"`
    Class    string `db:"class"`
    Profiles []Profile
}
type Profile struct {
    UID  int    `db:"uid"`
    Cid  int    `db:"cid"`
    Name string `db:"name"`
    Age  int    `db:"age"`
}

 

func main() {
    db := sqlx.MustOpen("mysql", "用户名:123456@tcp(127.0.0.1:3306)/xorm")
    defer db.Close()
    stmt, err := db.Query("SELECT * FROM class left join users on id=cid WHERE id=?", 1)
    if err != nil {
        fmt.Println(err)
    }
    var user User
    var profile Profile
    for stmt.Next() {
        err := stmt.Scan(&user.ID, &user.Class, &profile.UID, &profile.Name, &profile.Age, &profile.Cid)
        if err != nil {
            panic(err.Error())
        }
        user.Profiles = append(user.Profiles, profile)
    }

 

    b, _ := json.Marshal(&user)
    fmt.Println(string(b))
}
 
posted @ 2021-09-27 17:24  雪糕战士  阅读(399)  评论(0编辑  收藏  举报