douzi4724 2018-08-31 05:58
浏览 135

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

Here the code is written in Go. I am using two tables where one table has a foreign key that refers to the other table's primary key. Let's say I have a database as following struct defined:

   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"`
   }

And the sql schema is:

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)
)

Now while inserting in user by gorm as:

  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

It updates the row in user table but creates a new row in place table.But it should update the matching row in place table and not create a new one

Is there any way to do it? Here I am not using auto migrate function to create db tables.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在炒股软件中,爬到我想看的日k线
    • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
    • ¥15 seatunnel 怎么配置Elasticsearch
    • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
    • ¥15 (标签-MATLAB|关键词-多址)
    • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起