duangangmo0583 2018-11-03 14:55
浏览 98
已采纳

创建新结构并将其以一对多关系添加到数组

I'm trying to append a new item to an array in a one-to-many relationship. The problem is that one of the IDs is always undefined and the model I want to append to does not get updated.

I have the following models:

type Station struct {
    gorm.Model
    Name         string
    Measurements []Measurement
    PlantID      uint64
    Plant        Plant
}

type Measurement struct {
    ID             uint64 `gorm:"primary_key"`
    StationID      uint64
    TempSensor     float32
    LightSensor    float32
    HumiditySensor float32
    CreatedAt      time.Time
}

type Plant struct {
    gorm.Model
    Name string
}

This is the route to which I'm sending the post request:

/stations/:id/measurements

This is the current route handler that I have:

func CreateMeasurement(c *gin.Context) {
    id := c.Params.ByName("id")
    var station Station
    if err := db.Where("id = ?", id).First(&station).Error; err != nil {
        c.AbortWithStatus(404)
        fmt.Println(err)
    } else {
        var measurement Measurement
        c.BindJSON(&measurement)

        // Convert params string to uint
        convertedID, err := strconv.ParseUint(id, 10, 64)
        if err != nil {
            fmt.Println(err)
        }
        measurement.StationID = convertedID

        db.Model(&station).Association("Measurements").Append(&measurement)
        db.Save(&station)
        c.JSON(200, station)
    }
}

Question: How can I create a new Measurement item and append it to the []Measurement array in a specific Station which is specified by the route parameters?

  • 写回答

1条回答 默认 最新

  • duanlaiquan8174 2018-11-04 13:46
    关注

    Solved the problem. It turns out there was some problem with the database table. Although I got auto migrate enable, there was a problem with some ids that were null.

    Here is the working route:

    func CreateMeasurement(c *gin.Context) {
        id := c.Params.ByName("id")
        var station Station
        if err := db.Where("id = ?", id).First(&station).Error; err != nil {
            c.AbortWithStatus(404)
            fmt.Println(err)
        } else {
            var measurement Measurement
            c.BindJSON(&measurement)
    
            db.Model(&station).Association("Measurements").Append(&measurement)
            c.JSON(200, station)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办