Mysql 更新有效负载中包含的列

Mysql 更新有效负载中包含的列,mysql,rest,go,Mysql,Rest,Go,我有一个到mysql表的结构映射,如下所示,并希望更新PUT请求负载中发送的字段 type Notification struct { Id int64 `json:"id"` Type NotificationType Subject string `json:"confidence"` Body string `json:"body"` CreatedD

我有一个到mysql表的结构映射,如下所示,并希望更新PUT请求负载中发送的字段

type Notification struct {
 Id                 int64     `json:"id"`
 Type               NotificationType
 Subject            string    `json:"confidence"`
 Body               string    `json:"body"`
 CreatedDate        time.Time `json:"created_dt"`
 CreatedBy          int64     `json:"created_by"`
 ParentNotification int64     `json:"parent_id"`
 IsExpired          bool      `json:"expired"`
}
目前,我正在请求将所有字段包括在有效负载中,即使数据没有更改,并使用query with db.Execquery语句更新所有列

是否有任何方法可以让客户端只包含在有效负载中更改的字段,并只更新这些字段

{
 "body" : "new body"
 "subject" : "new subject"
}
我在db端使用以下软件包

"database/sql"
_ "github.com/go-sql-driver/mysql"

实现您想要的一种方法是,让客户机只发送他们想要更改的数据,即每个db表类型有一个额外的参数类型。因此,例如,给定您的通知类型,您的NotificationParams类型如下:

type NotificationParams struct {
    Id      int64 `json:"id"`
    // use pointers so that a field that is not present in the json
    // will result in a nil pointer value, which tells you that no
    // update is needed for that column, it also allows the client
    // to send an empty string if they want to delete the content of
    // some column, e.g. Body.
    Type    *NotificationType
    Subject *string `json:"confidence"`
    Body    *string `json:"body"`
    // and other fields that you want to allow the client change
}
然后在你的处理程序中,或者在任何地方,你都可以按照以下思路做一些事情:

params := &NotificationParams{} // unmarshal from json
notif := &Notification{} // read from db using params.Id

// change only those fields that were provided
if params.Type != nil {
    notif.Type = *params.Type
}
if params.Subject != nil {
    notif.Subject = *params.Subject
}
if params.Body != nil {
    notif.Body = *params.Body
}

// do some validation...

// if ok save notif using mysql UPDATE
使现代化 如果您想避免编写大量If语句,您可以编写两个setter或apply函数,无论您喜欢哪个名称,都可以为您这样做,一个用于您想要支持的每种类型,例如一个用于字符串,一个用于时间,等等

以这个函数为例:

// The variadic list of functions can be used to transform (think
// sanitization, normalization, etc.) the value before setting
// it to the dst pointer.
func ApplyStr(dst, src *string, fns ...func(string) string) {
    if src != nil {
        s := *src
        for _, fn := range fns {
            s = fn(s)
        }

        *dst = s
    }
}
然后您将使用类似于中的函数。

以下方法使用库在接收有效负载后保存数据:

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "time"
)


type NotificationType struct {
    gorm.Model

}

type Notification struct {
    gorm.Model
    Id                 int64     `json:"id"`
    Type               NotificationType
    Subject            string    `json:"confidence"`
    Body               string    `json:"body"`
    CreatedDate        time.Time `json:"created_dt"`
    CreatedBy          int64     `json:"created_by"`
    ParentNotification int64     `json:"parent_id"`
    IsExpired          bool      `json:"expired"`
}

func main() {
    //your handler code to receive and decode payload from client


    //save data to database
    db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        panic("failed to connect database")
    }
    defer db.Close()

    // Migrate the schema
    db.AutoMigrate(&Notification{})

    // Read
    var Notification notification
    db.First(&notification, 1) // find notification with id 1 , the id from your payload

    // Update the table from notification object
    db.Save(&notification)
}

要求客户机只包含有效负载中更改的字段并只更新这些字段是什么意思?您想要发送请求的方法还是如何处理请求?客户端程序可以将一个字段作为有效负载发送,或者将所有字段作为有效负载发送,并且在htt处理程序中,我需要更新它们发送的字段。如果有效负载是{body:newbody},那么query=updatetblsetbody=newbody,其中id=id。如果有效负载为{subject:new,body:new},则query=update tbl set subject=new,body=new,其中id=1意味着您可以将有效负载解码到通知结构并根据应用程序逻辑验证此结构,然后使用非空字段相应地更新数据库。谢谢mkopriva。这将起作用,我也在走同样的路。然而,我在检查我们是否可以通过减少if else来实现这一点。我在需要实现此功能的地方收到了大量put请求。再次感谢您的时间。@BinishJohn另外,如果您在解组之前有权访问旧记录,您可以将数据解组到其中。即:第一步从数据库中获取记录;第二步将json解组到其中。json解组器不会接触json中没有相应值的字段,而保留旧字段值不变。如果您需要保护某些字段不被更改,您可以将通知嵌入声明这些字段的结构中,然后解组器将设置这些字段,而不是通知本身上的字段。@BinishJohn在我前面的评论中举例说明了这个概念:谢谢:。解决它。我可以扩展它以适应我的服务。非常感谢