英文:
bun:go: how to change `belongs-to` relation mapping field in bun
问题
我正在处理一个在PostgreSQL中具有令人兴奋的数据库的项目。两个表之间存在关系,Order
和ResPartner
,其中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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论