【问题标题】:How to remove RETURNING clause in the Create method of gorm package?gorm包的Create方法中如何去掉RETURNING子句?
【发布时间】:2020-05-19 18:10:39
【问题描述】:

在为 gorm 包创建记录时,我对默认行为有点困惑。

city := models.City

if err := databases.DBGORM.Set("gorm:insert_option", "RETURNING *").Create(&city).Error; err != nil {
    fmt.Println(err.Error())
}

在日志中我看到这样的 SQL 查询:

INSERT INTO "my_scheme"."city" ("created_at","updated_at","deleted_at","name","country") VALUES ('2020-05-19 23:45:18','2020-05-19 23:45:18',NULL,'New York','USA') RETURNING * RETURNING "my_scheme"."city"."id"

从查询中可以看出,我有一个不正确的双 RETURNING 子句并引发错误。

在 SQL 查询末尾添加 id 似乎是 Create 方法的默认行为。我该如何改变这种行为?

models.go

package models

import (
    "my_app/proto"
    "time"
)

type City struct {
    Id uint64
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
    proto.City
}

func (City) TableName() string {
    return "my_scheme.city"
}

【问题讨论】:

  • 我无法更改 Create 函数的默认行为,但是您通过地址传递给 gorm 函数的结构将使用新 ID 和 created_at,updated_at 字段进行更新。您还需要插入行中的其他内容吗?

标签: sql go go-gorm


【解决方案1】:

不,没有办法改变这种行为。

但是如果你想在调用 Create 函数后获取 ID 或时间戳(CreatedAt 和 UpdatedAt),它们会在你的指针传递的模型中自动更新。

如果您有另一个具有默认值的字段,请将default 标记添加到模型中的该字段。在调用Create 之后,gorm 也会自动更新该字段。

type City struct {
    Id        uint64
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time

    SomeField *string `gorm:"default:test"`
}

// ...

city := models.City{}

if err := databases.DBGORM.Create(&city).Error; err != nil {
    fmt.Println(err.Error())
}

fmt.Printf("%+v", city)

[2021-04-13 21:39:44]  [1.06ms]  INSERT INTO "cities" ("created_at","updated_at","deleted_at") VALUES ('2021-04-13 21:39:44','2021-04-13 21:39:44',NULL) RETURNING "cities"."id"  
[1 rows affected or returned ] 

[2021-04-13 21:39:44]  [0.59ms]  SELECT "some_field" FROM "cities"  WHERE (id = 26)  
[1 rows affected or returned ] 

{
  "Id": 26,
  "CreatedAt": "2021-04-13T21:39:44.809605473+07:00",
  "UpdatedAt": "2021-04-13T21:39:44.809605473+07:00",
  "DeletedAt": null,
  "SomeField": "test"
}

如果您根本不想更新模型,请按值而不是指针将其传递给Create 方法,并忽略gorm.ErrUnaddressable 错误。

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多