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

feat: BeforeUpdate hook supports update using struct field value #7166

Closed
wants to merge 2 commits into from

Conversation

demoManito
Copy link
Member

@demoManito demoManito commented Aug 21, 2024

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

In the BeforeUpdate hook function, if the structure field value is updated and the field has the gorm:"column:field_name" set, the field is updated in SQL

User Case Description

  • Code:
type User struct {
	ID      int64 `gorm:"column:id;primary_key"`
	Version int64 `gorm:"column:version"`
	UserID  int64 `gorm:"column:user_id"`
}

// BeforeUpdate gorm hook
func (u *User) BeforeUpdate(*gorm.DB) error {
	u.Version = time.Now().Unix()
	return nil
}

func Update() error {
	return DB().Model(&User{}).Where("id = ?", 1).Update("user_id", 312123).Error
}
  • Expected Output:
UPDATE `user` SET `version`=1724247677,`user_id`=312123 WHERE id = 1

@demoManito demoManito self-assigned this Aug 21, 2024
@demoManito demoManito changed the title feat: BeforeUpdate hook supports update using struct feat: BeforeUpdate hook supports update using struct field value Aug 26, 2024
@jinzhu
Copy link
Member

jinzhu commented Sep 14, 2024

It's too tricky; it's not recommended to use Hooks for updating values. Instead, it's better to use SQL expressions.

@jinzhu jinzhu closed this Sep 14, 2024
@jinzhu jinzhu deleted the callback/update branch September 14, 2024 13:11
@demoManito
Copy link
Member Author

It's too tricky; it's not recommended to use Hooks for updating values. Instead, it's better to use SQL expressions.

ok thanks

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.

2 participants