Gorm 处理 HasOne 关系
Gorm handle HasOne relationship
我对 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
}
我想 SELECT 余额中 USD 字段大于 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 和 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
}
我想 SELECT 余额中 USD 字段大于 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
}