当前位置: > > > > Gorm 处理 HasOne 关系
来源:stackoverflow
2024-04-27 15:33:49
0浏览
收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Gorm 处理 HasOne 关系》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我在 gorm 和 mysql 方面遇到问题。我有这样的结构:
type Users struct { ID string Balance Balances Model } type Model struct { CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time } type Balances struct { UID string `gorm:"foreignkey:ID;unique_index"` USD int }
我想选择余额中美元字段大于 0 的用户。我该怎么做?
无论如何,db.find(&users)
获取所有用户,但不是他们的余额。事实上,执行的查询是:select * from users where users.deleted_at is null
解决方案
使用 .joins()
将 users
与 balances
连接,然后使用 .where()
使用条件
user := users{} db.joins("join balances on balances.uid = users.id").where("balances.usd > 0").find(&user)
更新: 尝试纠正您与预载平衡的关系
type Users struct { ID string Balance Balances `gorm:"foreignkey:UID;association_foreignkey:ID"` Model } type Balances struct { UID string `gorm:"unique_index"` USD int }
好了,本文到此结束,带大家了解了《Gorm 处理 HasOne 关系》,希望本文对你有所帮助!关注公众号,给大家分享更多Golang知识!