我對 GORM 和 MySQL 有疑問。我有這個結構:type Users struct {ID stringBalance BalancesModel}type Model struct {CreatedAt time.TimeUpdatedAt time.TimeDeletedAt *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
1 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
使用.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
}
- 1 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消