如何在 bun 中更改 `belongs-to` 关系映射字段?

huangapple go评论77阅读模式
英文:

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

问题

我正在处理一个在PostgreSQL中具有令人兴奋的数据库的项目。两个表之间存在关系,OrderResPartner,其中Order表具有ResPartner表的外键,外键列名为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"`
}

我尝试进行如下的查询:

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

但是出现了错误。

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

我认为bun试图查找一个名为contact_partner_id的字段。有没有办法覆盖字段名?

更新:我已经更新了我的问题。请参考这个示例仓库:go-db-test

英文:

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

答案1

得分: 2

你可以在bun中映射关系,例如:

属于(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"`
}
英文:

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"`
}

huangapple
  • 本文由 发表于 2021年9月30日 23:10:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69394675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定