卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34993本站已运行393

创建/更新时忽略createdAt字段,但返回JSON响应

创建/更新时忽略createdat字段,但返回json响应

在进行数据创建或更新操作时,有时我们希望忽略createdAt字段的值,而只是保留其默认值。这样做的目的是使得每次创建或更新数据时都使用相同的时间戳,而不会因为手动设置时间戳而导致数据不一致。同时,在返回JSON响应时,我们也希望保留createdAt字段的默认值。在PHP中,我们可以通过一些简单的操作来实现这一功能,从而提高代码的可读性和维护性。本文将为大家介绍如何在PHP中实现创建/更新时忽略createdAt字段,但在返回JSON响应时保留其默认值。

问题内容

我在 Go 中有一个结构

type ExternalSystem struct {
    ID        uint            `gorm:"primary_key"`
    Name      string          `json:"name" binding:"required"`
    CreatedAt *time.Time      `json:"createdAt" binding:"-"`
    DeletedAt *gorm.DeletedAt `json:"deletedAt" binding:"-"`
}

并有控制器(路线)

func CreateExternalSystemAction(c *gin.Context) {
    appG := app.Gin{C: c}

    externalSystem := models.ExternalSystem{}

    if err := c.ShouldBindJSON(&externalSystem); err != nil {
        appG.C.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
            "error": err.Error(),
        })
        return
    }

    db := models2.DB
    db.Create(&externalSystem)

    appG.C.JSON(http.StatusCreated, externalSystem)
}

func UpdateExternalSystemAction(c *gin.Context) {
    appG := app.Gin{C: c}
    db := models2.DB

    var externalSystem models.ExternalSystem

    db.Where("id = @id", sql.Named("id", c.Param("id"))).First(&externalSystem)

    if err := c.ShouldBindJSON(&externalSystem); err != nil {
        appG.C.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
            "error": err.Error(),
        })
        return
    }

    db.Updates(&externalSystem)

    appG.C.JSON(http.StatusOK, externalSystem)
}

创建或更新对象时如何忽略字段CreatedAt/UpdatedAt的完成?这样服务器(而不是客户端)负责填写这些字段,那么 JSON 会发送给我什么?但是,我需要该字段的值在响应中发送给客户端。

目前,当我发送 JSON 时:

{
    "name": "System 3",
    "createdAt": "2023-12-25T22:04:10.012034+04:00"
}

Gin 将此值绑定到结构体。再次总结一下,我想忽略这些写入字段(当从客户端收到时),但在读取响应中给出它们。

我尝试过:

绑定:“-”,但这不起作用(竞价验证)

json:“-”,但此隐藏响应字段

解决方法

我想了很长时间的解决方案。在阅读了我的问题下的评论后。我做出了一个完全适合我的选择。但是,该方法仍然与我在其他语言(PHP Symfony、Python Django)中使用的方法不相似

型号

type System struct {
    ID        uint
    Name      string
    CreatedAt time.Time
    UpdatedAt time.Time
}

type InputSystem struct {
    Name string
}

func (inputSystem *InputSystem) Convert() System {
    system := System{
        Name: inputSystem.Name,
    }
    return system
}

func (system *System) Save() (*System, error) {
    err := DB.Create(system).Error

    if err != nil {
        return &System{}, err
    }

    return system, err
}

func (system *System) BeforeSave(*gorm.DB) error {
    system.Name = html.EscapeString(strings.TrimSpace(system.Name))
    return nil
}

func (system *System) BeforeUpdate(*gorm.DB) error {
    system.Name = html.EscapeString(strings.TrimSpace(system.Name))
    return nil
}

控制器(路线)

func CreateSystemAction(c *gin.Context) {

    var inputSystem models.InputSystem

    if err := c.BindJSON(&inputSystem); err != nil {
        c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
            "error": err.Error(),
        })
        return
    }

    dbSystem := inputSystem.Convert()

    _, err := dbSystem.Save()
    if err != nil {
        return
    }

    c.JSON(http.StatusCreated, dbSystem)
}

如果有更好的建议,我将很高兴收到评论

卓越飞翔博客
上一篇: 无法使用 go-github 和 422 创建提交 - 更新不是快进
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏