Gorm handle HasOne关系

问题描述 投票:0回答:1

我对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

mysql go go-gorm
1个回答
0
投票

使用.Joins()UsersBalances连接,然后使用条件使用.Where()

user := Users{}
db.Joins("JOIN balances ON balances.uid = users.id").Where("balances.usd > 0").Find(&user)
© www.soinside.com 2019 - 2024. All rights reserved.