简体   繁体   中英

bun:go: how to change `belongs-to` relation mapping field in bun

I am working on bun that has an execting database in PostgreSQL. There was a relationship between the two tables. Order and ResPartner where Order table has a foreign key of ResPartner table having column name contact_partner

type Order struct {
    bun.BaseModel    `bun:"select:sb_order"`
    ID               int64       `bun:"id"`
    GenOid           string      `bun:"gen_oid"`
    ContactPartner   *ResPartner `bun:"rel:belongs-to"`
    ContactPartnerID int64       `bun:"contact_partner"`
}
type ResPartner struct {
    bun.BaseModel `bun:"select:sb_partner"`
    ID            int64  `bun:"id"`
    Name          string `bun:"name"`
}

I try to make queries like this.

err = db.NewSelect().Model(&order).
        Relation("ContactPartner").
        Scan(ctx)

But it is giving error.

reflect: call of reflect.Value.Field on ptr Value

I think bun try to find a field name like contact_partner_id . Is there any way to override the field name?

UPDATE: I have updated my question. see this repo for example: go-db-test

You can map relationships in a bun:go something like:

belongs-to:

 type User struct {
      ID        int64 `bun:",pk"`
      Name      string
      ProfileID int64
      Profile   *Profile `bun:"rel:belongs-to,join:profile_id=id"`
    }

has-one:

type User struct {
    ID      int64 `bun:",pk"`
    Name    string
    Profile *Profile `bun:"rel:has-one,join:id=user_id"`
}

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