如何删除gorm包的create方法中的returning子句?

6qfn3psc  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(755)

在为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 不正确并引起错误的子句。
添加 id 在sql查询的末尾,似乎是 Create 方法。我怎样才能改变这种行为?
型号.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"
}
3npbholx

3npbholx1#

不,没有办法改变这种行为。
但是,如果您想在调用create函数之后获取id或时间戳(createdat和updatedat),它们将在指针传递的模型中自动更新。
如果有另一个字段具有默认值,请添加 default 标记到模型中的此字段。在调用之后,gorm也会自动更新该字段 Create .

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 错误。

相关问题