简体   繁体   中英

How do I run go-pg orm QueryContext function for nested struct?

When I try QueryContext function with nested struct , nested struct always get empty struct . How I solve this?

type User struct {
    Firstname    *string    `json:"firstname" sql:",notnull"`
    Lastname     *string    `json:"lastname" sql:",notnull"`
}

type TestUser struct {
    User *User `json:"user"`
}

query := `
SELECT
users.firstname,
users.lastname
FROM
    test_users
    LEFT JOIN (
        SELECT
        id, firstname, lastname
        FROM
            users
    ) users ON users.id = test_users.user_id
LIMIT 1
`

models := []TestUser{}
_, _ := conn.QueryContext(ctx, &models, query)
    return models, nil

If this is impossible with go-pg orm, Is there any orm function to do that sql ?

Thanks

You have to use the ORM model abstraction provided by go-pg .

If you have two structs like these:

type User struct {
    Firstname    *string    `json:"firstname" sql:",notnull"`
    Lastname     *string    `json:"lastname" sql:",notnull"`
}

type TestUser struct {
    User *User `json:"user"`
}

Then you can populate your models slice using the .Model

pgdb := pg.Connect(......)
models := []TestUser{}

err =pgdb.Model(&models).Relation("User").Select()
if err != nil {
    log.fatal(err)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM