【问题标题】:Gorm handle HasOne relationshipGorm 处理 HasOne 关系
【发布时间】:2020-04-11 00:59:46
【问题描述】:

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

    使用.Joins()UsersBalances 连接起来,然后使用.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
    }
    

    【讨论】:

    • 这行得通,但我在用户中的余额结构是空的。有没有办法在其中包含 usd 值?
    • @Rockietto 你可以在.Join() 之前使用.Preload("Balances") 来加载平衡
    • 刚试过这个db.Debug().Preload("Balances").Joins("JOIN balances ON balances.uid = users.id").Where("balances.usd > 0").Find(&users)但返回can't preload field Balances for structs.Users
    • 试过这个db.Debug().Preload("Balance").Joins("JOIN balances ON balances.uid = users.id").Where("balances.usd > 0").Find(&users),得到这个错误can't preload field Balance for structs.Users。我还尝试将Preload("Balance") 放在Find 之前,但错误相同。
    • 可能是用户和余额之间的关系问题
    猜你喜欢
    • 2014-11-08
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2018-05-29
    • 2021-08-15
    • 2017-04-21
    • 2016-03-17
    相关资源
    最近更新 更多