Gorm和协会

6qftjkof  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(156)

我试图弄清楚如何加载与gorm的关联。文档不是很好。
我有模特:

type Account struct {
    gorm.Model
    Name          string `gorm:"column:name;unique_index;not null;size:255"`
    AccountTypeID uint   `gorm:"not null"`
    UserID        uint   `gorm:"not null"`
    AccountType   accounttypes.AccountType
}

以及

type AccountType struct {
    gorm.Model
    Name string `gorm:"column:name;unique_index;not null;size:255"`
    Type string `gorm:"column:type;unique_index;not null;size:255"`
}

所以每个Account都有一个关联的Account Type
当我尝试通过以下方式加载数据时:

func GetAccounts(userId uint) ([]Account, error) {
    db := common.GetDB()
    var model []Account
    db.LogMode(true)
    err := db.Model(&Account{}).Where("accounts.user_id =?", userId).Related(&accounttypes.AccountType{}, "AccountTypes").Error
    return model, err
}

以下是输出:

有人能解释一下如何正确地做这件事的'gorm方式'?

8i9zcol2

8i9zcol21#

您可以使用clause.Associations,如下所示:www.example.comhttps://gorm.io/docs/preload.html#Preload-All
clause.Associations可以像Select一样在创建/更新时与Preload一起工作,您可以使用它来Preload所有关联
注:
clause.Associations不会预加载嵌套关联,但您可以将其与Nested Preloading一起使用
我还没有测试过,但也许你需要这样的东西:

var userAccounts []Account
err := db.Where("accounts.user_id =?", userId).Preload(clause.Associations).Find(&userAccounts).Error

Where的情况可能是Where(&Account{UserID: userId})
clause.Associations可以用于预加载所有关联。如果您想预加载一个项目,有Preload(Item)方法。在您的情况下:Preload("AccountType")

db.Where(&Account{UserID: userId}).Preload("AccountType").Find(&userAccounts).Error

相关问题