登录
首页 >  Golang >  Go问答

如何使用gorm更新sql中的嵌套表?

来源:stackoverflow

时间:2024-04-13 09:54:36 400浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何使用gorm更新sql中的嵌套表?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

这里的代码是用go编写的。我正在使用两个表,其中一个表具有引用另一个表的主键的外键。假设我有一个定义如下结构的数据库:

type user struct{
       id uint `gorm:"primary_key;column:id"`
       name string `gorm:"column:name"`
       place place
       placeid
   }

   type place struct{
       id uint `gorm:"primary_key;column:id"`
       name string `gorm:"column:name"`
       pincode uint `gorm:"column:pincode"`
   }

sql 架构是:

create table place(
    id int(20) not null auto_increment,
    name varchar(100) not null,
    pincode uint(20) not null,
    primary key (id),
)

create table user(
    id int(20) not null auto_increment,
    name varchar(100) not null,
    place_id uint(20) not null,
    primary key (id),
    foreign key (place_id) references place(id)
)

现在,当 gorm 插入用户时:

place := Place{Name:"new delhi",Pincode:1234}
  user := User{Name: "sam", Age: 15, Place: place}
  err = db.Debug().Create(&user).Error

  //It  inserts to both user and place table in mysql
  //now while updating to name in user table as Samuel and place as 
  //following

  place := Place{Name:"mumbai",Pincode:1234}
  err = db.Debug().Model(&User{}).Where("id =?", 
   1,).Update(&user{Name:"Samuel",Place:place}).Error

它更新用户表中的行,但在位置表中创建一个新行。但它应该更新位置表中的匹配行,而不是创建新行

有什么办法吗?这里我没有使用自动迁移功能来创建数据库表。


解决方案


您的问题的答案应该在关系或Association Mode中寻求。 下面的示例展示了如何为多对多添加新关联,有很多,替换多对多的当前关联strong>有一个属于

db.Model(&user).Association("Place").Append(Place{Name:"mumbai",Pincode:1234})

或者您可以用新的关联替换当前的关联:

db.model(&user).association("place").replace(place{name:"孟买",pincode:1234},place{name:"新德里",pincode:1234})

今天关于《如何使用gorm更新sql中的嵌套表?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>