Skip to content

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

Open
@Omkarz7

Description

@Omkarz7
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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions