gorm不会更新时间戳字段。

huangapple go评论97阅读模式
英文:

gorm does not update timestamp field

问题

这是我的模型:

type User struct {
    ID          uuid.UUID   `gorm:"primarykey;column:id;type:uuid;default:gen_random_uuid()"`
    FullName    string      `gorm:"column:full_name"`
    PhoneNumber string      `gorm:"column:phone_number"`
    JoinDate    pq.NullTime `gorm:"column:join_date"`
}

我使用以下 SQL 创建了数据库:

CREATE TABLE IF NOT EXISTS "fellowship"."users" (
    "id"           uuid      NOT NULL DEFAULT uuid_generate_v4(),
    "full_name"    text      NOT NULL,
    "phone_number" text      NOT NULL,
    "join_date"    timestamp,
    "created_at"   timestamp NOT NULL DEFAULT NOW(),
    "updated_at"   timestamp NULL     DEFAULT NOW(),

    PRIMARY KEY ("id")
);

如果我更新 join_date 字段,尽管没有返回错误,但数据库中的值仍然保持为 null:

func UpdateUser(user *models.User) error {
    fmt.Println("repo: user id:", user.ID)
    fmt.Println("repo: user join date:", user.JoinDate)

    result := tx.Save(user)

    fmt.Println("result.RowsAffected:", result.RowsAffected)
    fmt.Println("result.Error:", result.Error)

    if result.Error != nil {
        return ParseError(result.Error)
    }

    if result.RowsAffected == 0 {
        return ErrRecordNotFound
    }

    return nil
}

日志输出为:

repo: user id: 2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102
repo: user join date: {2023-09-25 00:00:00 +0000 UTC false}
result.RowsAffected: 1
result.Error: <nil>

但数据库中的 join_date 列仍然为 null:

postgres=# select id, join_date, created_at from fellowship.users where id = '2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102';
                  id                  | join_date |         created_at         
--------------------------------------+-----------+----------------------------
2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102 |           | 2023-08-08 15:12:37.001919
(1 row)

这个问题只影响日期字段,其他列可以成功更新。

编辑 1:

我还检查了 sql.NullTime 类型,结果是相同的。

英文:

This is my model:

type User struct {
	ID          uuid.UUID   `gorm:&quot;primarykey;column:id;type:uuid;default:gen_random_uuid()&quot;`
	FullName    string      `gorm:&quot;column:full_name&quot;`
	PhoneNumber string      `gorm:&quot;column:phone_number&quot;`
	JoinDate    pq.NullTime `gorm:&quot;column:join_date&quot;`
}

And I have created my database using this SQL:

CREATE TABLE IF NOT EXISTS &quot;fellowship&quot;.&quot;users&quot; (
    &quot;id&quot;           uuid      NOT NULL DEFAULT uuid_generate_v4(),
    &quot;full_name&quot;    text      NOT NULL,
    &quot;phone_number&quot; text      NOT NULL,
    &quot;join_date&quot;    timestamp,
    &quot;created_at&quot;   timestamp NOT NULL DEFAULT NOW(),
    &quot;updated_at&quot;   timestamp NULL     DEFAULT NOW(),

    PRIMARY KEY (&quot;id&quot;)
);

If I update the join_date field, the value remains null in the database; even though no errors return:

func UpdateUser(user *models.User) error {
	fmt.Println(&quot;repo: user id: &quot;, user.ID)
	fmt.Println(&quot;repo: user join date: &quot;, user.JoinDate)

	result := tx.Save(user)

	fmt.Println(&quot;result.RowsAffected:&quot;, result.RowsAffected)
	fmt.Println(&quot;result.Error:&quot;, result.Error)

	if result.Error != nil {
		return ParseError(result.Error)
	}

	if result.RowsAffected == 0 {
		return ErrRecordNotFound
	}

	return nil
}

The logs are:

repo: user id:  2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102
repo: user join date:  {2023-09-25 00:00:00 +0000 UTC false}
result.RowsAffected: 1
result.Error: &lt;nil&gt;

And the database join_date column remains null:

postgres=# select id, join_date, created_at from fellowship.users where id = &#39;2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102&#39;;
                  id                  | join_date |         created_at         
--------------------------------------+-----------+----------------------------
 2e1b0c0b-ea3f-4ddd-a022-a59cdbbcf102 |           | 2023-08-08 15:12:37.001919
(1 row)

This issue only affects the date fields and other columns update successfully.

Edit 1:

I have also checked type sql.NullTime. Result was the same.

答案1

得分: 1

日志给出了一个很大的提示。pq.NullTime 是这样定义的:

type NullTime struct {
    Time  time.Time
    Valid bool // 如果 Time 不为 NULL,则 Valid 为 true
}

而在你的日志中,它显示为:

user join date:  {2023-09-25 00:00:00 +0000 UTC false}

这意味着你有一个(基本上)这样的结构:

JoinTime := pq.NullTime{
    Time: "2023-09-25 00:00:00 +0000 UTC",
    Valid: false,
}

其中 Valid: false 表示“该字段为空”。

英文:

The log gives you a big hint. A pq.NullTime is

type NullTime struct {
    Time  time.Time
    Valid bool // Valid is true if Time is not NULL
}

and in your log it says

user join date:  {2023-09-25 00:00:00 +0000 UTC false}

which means you have (essentially):

JoinTime := pq.NullTime{
    Time: &quot;2023-09-25 00:00:00 +0000 UTC&quot;,
    Valid: false,
}

where Valid: false means "this field is null"

huangapple
  • 本文由 发表于 2023年8月8日 22:42:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定