doudao7511 2019-07-27 16:38
浏览 233

用GORM中的关联创建记录?

I am working on a project and relatively new to Golang. I am using GORM for my Database ORM. I don't know what I am doing wrong but I can't get to create records with associations.

type (
    Task struct {
        gorm.Model
        Title       string    `json:"title"`
        Description string    `json:"description"`
        Priority    Priority  `json:"priority_id" validate:"required" gorm:"foreignkey:PriorityID"`
        PriorityID  uint
    }

    Priority struct {
        gorm.Model
        Name      string     `json:"name"`
    }
)

And when I do

task := Task{
    Title:       "Test Task!",
    Description: "Test Task Description",
    Priority:    Priority{ID: 1},
}
db.Create(&task)

It throws me this error:

[2019-07-27 18:34:35] sql: converting argument $7 type: unsupported type models.Priority, a struct

I had a look at GORM Associations but couldn't really find any solution which could make it work.

  • 写回答

1条回答 默认 最新

  • dongni3854 2019-07-29 11:47
    关注

    Gorm is and object-relational mapping (ORM) framework for Go. To create a record with association use something like this:

    type (
        Task struct {
            Title       string    `gorm:"column:title"`
            Description string    `gorm:"column:description"`
            PriorityID  int64     `gorm:"column:priority_id"`
            Priority    Priority  `gorm:"foreignkey:PriorityID"`
        }
    
        Priority struct {
            ID        int64      `gorm:"primary_key"`
            Name      string     `gorm:"column:name"`
        }
    )
    

    Then try to add

    
    task := Task{
        Title:       "Test Task!",
        Description: "Test Task Description",
        Priority:    Priority{ID: 1},
    }
    db.Create(&task)
    
    

    Please use this link for refer : Gorm Documentation

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看