alvoff
alvoff

Reputation: 11

How can I querying a subfield in nested structures in go-pg (Postgres ORM with Go)?

I am new to SQL ORM databases and I'm writing code in Golang which works with PostgresQL database. I have this nested structures:

type PersonalInfo struct {
    Name      string `sql:"name"`
    Telephone string `sql:"telephone"`
    Email     string `sql:"email"`
    Age       string `sql:"age"`
    Gender    string `sql:"gender"`
    City      string `sql:"city"`
}

type DB_SessionInfo struct {
    Coockie string
}

type DB_User struct {
    ID           int            `sql:"id, pk"`
    Username     string         `sql:"username,unique"`
    Password     string         `sql:"password"`
    PersonalInfo PersonalInfo   `sql:"personalinfo, type:jsonb"`
    SessionInfo  DB_SessionInfo `sql:"session_info, type:jsonb"`
}

If I'm trying to select item by username, I use the code above and it works well:

func (u *DB_User) GetItemByName(db *pg.DB) error {
    err := db.Model(u).Where("username = ?0", u.Username).Select()
    if err != nil {
        fmt.Printf("Error while getting value by *username*. Reason: %v\n", err)
        return err
    }
    fmt.Printf("Get by *username* successful for <%v>\n", u)
    return nil
}

Before every request to database i connect to this and create tables by code above:

func someFunction() {
    database := ConnectToDB()
    defer database.Close()

    // some code
    DB_Entry := new(db.DB_User)
    DB_Entry.Username = "Username"

    DB_Entry.GetItemByName(database)
}

func ConnectToDB() *pg.DB {
    database := pg.Connect(&pg.Options{
        User:     "postgres",
        Password: "postgres",
        Database: "postgres",
    })
    fmt.Println("\nSuccessful connection to DB")

    err := createSchema(database)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("Schema created")
    }
    return database
}

func createSchema(database *pg.DB) error {
    for _, model := range []interface{}{(*db.DB_User)(nil), (*db.PersonalInfo)(nil)} {
        err := database.CreateTable(model, &orm.CreateTableOptions{
            IfNotExists: true,
        })
        if err != nil {
            return err
        }
    }
    return nil
}

So, when I want to Select item where personalinfo.name == "some_name" by this code I have error. Code:

func (u *DB_User) AnotherGetItemByName(db *pg.DB) error {
    err := db.Model(u).Where("personalinfo.name = ?0", u.PersonalInfo.Name).Select()
        return err
    }
    return nil
}

Error:

ERROR #42P01 table "personalinfo" doesn`t exist

So my question is, what I am doing wrong? Wrong request in select function? Maybe the mistake in creating tables in function createSchema?

I was trying to find an answer in stackoverflow and reading go-pg documentation, but can't find the solution. I'm sure that has very simple solution and it is basic point of using sql, but i'm new in it. I will be appreciated for help.

Upvotes: 1

Views: 1601

Answers (1)

Kern
Kern

Reputation: 868

You need to tell the ORM to make a JOIN statement on the PersonalInfo table using the Relation method (Column on older versions of go-pg).

func (u *DB_User) AnotherGetItemByName(db *pg.DB) error {
    err := db.Model(u).Relation("PersonalInfo").Where("PersonalInfo.name = ?", u.PersonalInfo.Name).Select()
        return err
    }
    return nil
}

Upvotes: 1

Related Questions