Skip to content

about the execution order of the BeforeDelete hook when performing a soft delete #7691

@Iristack

Description

@Iristack

Your Question

Hi everyone,

I'm encountering an issue while using GORM's soft delete feature.

I have a field defined like this:

DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index"`

And a hook like this:

func (t *TenantInfo) BeforeDelete(tx *gorm.DB) error {
    if currentUser, ok := getCurrentUserFromContext(tx); ok {
        t.DeletedBy = currentUser
    }
    return nil
}

I want to record the user who performed the deletion during the delete operation. However, I noticed that the actual SQL being executed is:

UPDATE `table_name` SET `deleted_at`="2026-01-14 19:32:47.266" WHERE `table_name`.`id` = 9 AND `table_name`.`deleted_at` IS NULL

This is my deletion code:

if err := databases.GetDB().WithContext(ctx).Delete(&tenant).Error; err != nil {
    logger.GetRuntime().Error("delete tenant failed", zap.Error(err))
    return
}

The update does not include the changes I made in the BeforeDelete hook (e.g., setting DeletedBy).
I also tried fetching the record first and then deleting it, but the same issue persists.

Is this behavior expected? And are there any alternative solutions or workarounds?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions