Skip to content

Save bug #797

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Save bug #797

wants to merge 2 commits into from

Conversation

lz-freedom
Copy link

@lz-freedom lz-freedom commented Apr 8, 2025

Explain your user case and expected results

当字段带有默认值,gorm-gen在save的时候,会把零值更新为默认值,在gorm里面没有这个问题

测试表:

CREATE TABLE `gorm_test_user_tmp` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `status` int NOT NULL DEFAULT '1',
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Model:

type User struct {
	gorm.Model
	Username string `gorm:"column:username;not null;" json:"username"`
	Status   int    `gorm:"column:status;not null;default:1" json:"status"`
}

func (User) TableName() string {
	return "gorm_test_user_tmp"
}

测试代码

func TestPl(t *testing.T) {
	ctx := context.Background()
	qUser := query.Use(db).User
	// 创建一个新的用户
	newUser := &model.User{
		Username: "test",
	}
	if err := qUser.WithContext(ctx).Debug().Create(newUser); err != nil {
		t.Error(err)
	}
	// 更新所有状态为0
	if _, err := qUser.WithContext(ctx).Debug().Where(qUser.Status.Gt(0)).Update(qUser.Status, 0); err != nil {
		t.Error(err)
	}

	// 查询当前用户状态
	user, err := qUser.WithContext(ctx).Debug().Where(qUser.ID.Eq(newUser.ID)).First()
	if err != nil {
		t.Error(err)
	}
	t.Logf("befer save status: %d", user.Status)

	// 修改username并使用 save 保存
	user.Username = "test2"
	if err = qUser.WithContext(ctx).Debug().Save(user); err != nil {
		t.Error(err)
	}

	// 查询最新的状态
	user, err = qUser.WithContext(ctx).Where(qUser.ID.Eq(newUser.ID)).First()
	if err != nil {
		t.Error(err)
	}
	t.Logf("after save status: %d", user.Status)
}

测试结果:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant