Skip to content
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

"BeforeUpdate" hook not working for individual column updates #1943

Open
Omkarz7 opened this issue Feb 24, 2022 · 0 comments
Open

"BeforeUpdate" hook not working for individual column updates #1943

Omkarz7 opened this issue Feb 24, 2022 · 0 comments

Comments

@Omkarz7
Copy link

Omkarz7 commented Feb 24, 2022

type User struct {
	ID        int64
	CreatedAt time.Time `sql:"default:now()"`
	UpdatedAt time.Time `sql:"default:now()"`
	Name      string
	Email    string
}

func (m *User) BeforeUpdate(ctx context.Context) (context.Context, error) {
	m.UpdatedAt = timeNow().Round(time.Microsecond)
	return ctx, nil
}

The following two queries don't update the updated_at column

user := &User{ID:1, Email:"[email protected]"} 
_, err := db.ModelContext(ctx, user).Column("email").Where("id = ?", user.ID).Update()
_, err := db.ModelContext(ctx, user).Set("email = ?",users.Email ).Where("id = ?", user.ID).Update()

The below queries work fine and update the updated_at column

user := &User{ID:1, Email:"[email protected]"} 
_, err := db.ModelContext(ctx, user)..WherePK().UpdateNotZero()
_, err := db.ModelContext(ctx, user).Where("id = ?", id).Update()

Is this intended behavior where BeforeUpdate hook is only triggered and used when the values are updated using struct?
Is it possible to have a update tag which updates the updated_at column if it exists. Similar to how soft delete works, where we update deleted_at is set to current time if the column exists and we mention the tag in struct.

@Omkarz7 Omkarz7 changed the title "BeforeUpdate" not working individual column updates "BeforeUpdate" hook not working for individual column updates Feb 24, 2022
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

No branches or pull requests

1 participant