简体   繁体   中英

go-pg got doesn't has relation thought on my table has relation

i have a contacts relation to provinces, and here is on my struct

    Contact struct {
        tableName       struct{}    `pg:"contacts,discard_unknown_columns"`
        ID              int         `json:"id"`
        Address         string      `json:"address"`
        BuildingType    string      `json:"building_type"`
        BuildingNumber  float64     `json:"building_number"`
        Province        *Province   `pg:"fk:province_id" json:"province"`
    }

    Province struct {
        tableName      struct{}         `pg:"provinces,discard_unknown_columns"`
        ID             int              `json:"id" pg:",pk"`
        Name           string           `json:"name"`
    }

and here how i call:

    var us Contact
    err = db.Model(&us).Relation("provinces").Where(
        "id = ?", 3,
    ).Select()

what i go is model=Contact does not have relation="provinces" how to correct way to query this with go-pg?

when i change tag on Contact for Province with tag pg:"rel:has-one"

i got this error pg: Contact has-one Province: Contact must have column province_id (use fk:custom_column tag on Province field to specify custom column)

note: i dont use their migration, i use sql-migration for all migrations

As stated in the error and the docs, you need to have a province_id column on Contact :

Contact struct {
    tableName       struct{}    `pg:"contacts,discard_unknown_columns"`
    ID              int         `json:"id"`
    Address         string      `json:"address"`
    BuildingType    string      `json:"building_type"`
    BuildingNumber  float64     `json:"building_number"`
    ProvinceId      int         
    Province        *Province   `pg:"rel:has-one" json:"province"`
}

If your ref column name is not province_id then you can use another column and add fk:custom_column to it.

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