删除无效

Why can't I remove record from mysql database using .Delete()?

Here is an example:

tx := db.Begin()
if err := tx.Delete(&User{}, id).Error; err != nil {
  fmt.Print(err)
  tx.Rollback()
} else {
  fmt.Print("Rows affected: %d", tx.RowsAffected) // Always returns 0
  tx.Commit()
}

Using tx.First(&user, id) works and return user correctly

I tried:
tx.Unscoped().Delete(...) also not working
tx.Exec("delete from users where (id = ?)", id) RowsAffected = 0
tx.First(&user, id); tx.Delete(&user) not working

p.s. User with id id exists in database

// First Find record and that struct to use for delete user:

 tx := db.Begin()

  // Read
  var user User
  tx.First(&user, id) // find product with id 1

  // Delete - delete user
  //tx.Delete(&user)

if err := tx.Delete(&user).Error; err != nil {
  fmt.Print(err)
  tx.Rollback()
} else {
  fmt.Print("Rows affected: %d", tx.RowsAffected) // Always returns 0
  tx.Commit()
}

When I upgrade to v1.9.x, DELETE() is not working. And I rollback to v1.0, it worked correctly.

After turning on DB Log, I found it's gorm v1.9 new feature: Auto Create/Update

Reference is here: http://gorm.io/docs/associations.html#Auto-Create-Update

So if you update field after deleting something, it will insert data back into database.

try skip Auto Create/Update like this.

db.Set("gorm:association_autoupdate", false).Set("gorm:association_autocreate", false).Create(&user)