Reputation: 109
I have a problem with GORM and MySQL. I have this structure:
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
}
I would like to SELECT users which have the USD field of their balance greater than 0. How can I do that?
Anyway, db.Find(&users)
get all users, but not their balance. In fact, the query executed is: SELECT * FROM users WHERE users.deleted_at IS NULL
Upvotes: 1
Views: 243
Reputation: 18430
Use .Joins()
to join Users
with Balances
then use condition using .Where()
user := Users{}
db.Joins("JOIN balances ON balances.uid = users.id").Where("balances.usd > 0").Find(&user)
Update: Try to correct your relation to preload balance
type Users struct {
ID string
Balance Balances `gorm:"foreignkey:UID;association_foreignkey:ID"`
Model
}
type Balances struct {
UID string `gorm:"unique_index"`
USD int
}
Upvotes: 1