我对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
}
我想选择余额中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)