Home > Net >  Gorm Association Delete does not remove rows, instead update rows
Gorm Association Delete does not remove rows, instead update rows

Time:10-25

A client has many TenantRoles. I want to delete all TenantRoles once a client is deleted.

 type Client struct {
        Id                          string `gorm:"primaryKey"`
        CreatedAt                   time.Time
        UpdatedAt                   time.Time
        TenantRoles []roles.TenantRole
    }
    
    type TenantRole struct {
        Id        uint `gorm:"primarykey"`
        CreatedAt time.Time
        UpdatedAt time.Time
    
        ClientID string
    }
    
    return db.Transaction(func(tx *gorm.DB) error {
            err = db.Model(&clientToRemove).Association("TenantRoles").Delete(&clientToRemove.TenantRoles)
            if err != nil {
                return err
            }
    
            err = db.Delete(&clientToRemove).Error
            if err != nil {
                return err
            }
    
            return nil
        })

I expect related rows in tenant_role to be removed, instead of delete query, it executes an update query to remove client_id.

[210.834ms] [rows:1] UPDATE "tenant_role" SET "client_id"=NULL WHERE "tenant_role"."client_id" = 'xxxxxxxxxxx' AND "tenant_role"."id" = 9

How to completely remove rows in associated tenant_role table?

Database is Postgres

CodePudding user response:

As stated in the documentation, the delete with association operation will just remove the references between Client and TenantRole. In your case, it just updated the TenantRole records to set the client_id to NULL.

If you want to delete the objects as well, you can try using Select with the delete operation. Please note that this only works if the primary key is not zero, so your query might look something like this:

err = db.Select("TenantRoles").Delete(&Client{Id: clientId}).Error

or just use clientToRemove if it already has the Id field populated

err = db.Select("TenantRoles").Delete(&clientToRemove).Error
  • Related