douyi1855 2018-12-13 17:09
浏览 24

Golang GORM有很多关系

I have 2 simple entities, User has many Assets:

type User struct {
    UserId     int     `gorm:"PRIMARY_KEY"`
    Email      string  `gorm:"column:email"`
    FirstName  string  `gorm:"column:firstname"`
    LastName   string  `gorm:"column:lastname"`
    Assets     []Asset `gorm:"foreignkey:user_id"`
}

type Asset struct {
    AssetId int    `gorm:"PRIMARY_KEY"`
    UserId  int    `gorm:"column:user_id"`
    Slug    string `gorm:"column:slug"`
    Address string `gorm:"address"`
}

I want to get a user by the primary id and also collect the assets.

Following the documentation here: http://doc.gorm.io/associations.html#has-many I did the following which gives me an empty array although there are records:

var user app.User
var assets []app.Asset

err := r.DB.Where("user_id = ?", userId).First(&user).Error
if err != nil {
    return nil, err
}

r.DB.Model(&user).Related(&assets)

Changing from:

r.DB.Model(&user).Related(&assets)

to:

r.DB.Model(&user).Related(&user.Assets)

I retrieve a single Asset because GORM is retrieving by asset_id instead of by user_id for some reason. (so if the user_id is 10, it is getting an asset with asset_id -> 10)

What is the correct way to handle the relationship in this case ?

  • 写回答

2条回答 默认 最新

  • dongzouxigu12345 2018-12-13 18:13
    关注

    I tried this that way too based on the docs and was unable to get it to work.

    What ultimately worked for me was the Preload() func on the db.

    Here's an example from some of my code:

    err := GetDB().Preload("Ingredients").Find(&flavors).Error
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法