如何使用 GORM 处理对应于数据库模式的 JSON?

How to handle with GORM a JSON that corresponds to a database schema?

我正在编写一个后端 API,它从数据库(由 GORM 处理)向前端发送一些 JSON 数据。前端在对字段内容进行一些修改后,也将数据发回给我 JSON.

下面是代码的模型

package main

import (
    "encoding/json"
    "fmt"

    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type User struct {
    ID     uint
    Name   string
    Card   Card
    CardID uint
}

type Card struct {
    ID     uint
    Number string
}

func main() {
    // initialize the database
    db, _ := gorm.Open(sqlite.Open("mytest.sqlite"), &gorm.Config{})
    db.Debug()
    db.AutoMigrate(&User{}, &Card{})
    // create two cards
    db.Create(&Card{
        Number: "42",
    })
    db.Create(&Card{
        Number: "100",
    })
    // find one of them
    var myCard Card
    db.Where(map[string]interface{}{"number": "42"}).First(&myCard)
    // create a user with that card
    db.Create(&User{
        Name: "john",
        Card: myCard,
    })
    // find that user
    var myUser User
    db.Preload("Card").Where(map[string]interface{}{"name": "john"}).Last(&myUser)
    // this is then marshalled to JSON, and sent to a frontend.
    // on that frontend there are some changes and I get back the JSON
    // this is simulated below:
    // the card itself changed
    myUser.Card.ID = "2"
    myUser.Card.ID = "100"
    // the name of the user changed
    myUser.Name = "mary"
    output, _ := json.Marshal(myUser)
    fmt.Print(string(output))
    // Now output holds the JSON string
}

// output
// {"ID":12,"Name":"mary","Card":{"ID":2,"Number":"100"},"CardID":1}

我的问题是如何处理output才能写回数据库

我不太了解 GORM(或 ORM),我不明白如何处理以下事实:

特别是,我不明白 GORM 是否会“知道”附加的卡现在不同了(并且对应于数据库中的卡)。我相信 Name 改变的事实不是问题(因为 ID 是一样的)

您可以将 JSON 主体解码为用户结构,然后对其进行更新。

func patchUser(w http.ResponseWriter, r *http.Request) {
    // get the id from the url i.e. /users/1
    // you need to use a framework or implement this yourself
    id := getId(r.URL)

    // decode the body into a new user
    patch := User{}
    json.NewDecoder(r.Body).Decode(&patch)
    
    // patch the user at the given id
    db.Model(User{}).Where("id = ?", id).Updates(patch)
}

您可以在此处找到有关更新的文档:https://gorm.io/docs/update.html