Reputation: 1789
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
Upvotes: 3
Views: 4440
Reputation: 48396
Please try to delete the user through
var u User
db.Unscoped().Delete(&u, "id = ? ", id)
Upvotes: 0
Reputation: 4171
Try this one:
tx := db.Begin()
delTx := tx.Delete(&User{}, id)
if err := delTx.Error; err != nil {
fmt.Print(err)
tx.Rollback()
} else {
fmt.Print("Rows affected: %d", delTx.RowsAffected)
tx.Commit()
}
Upvotes: 0
Reputation: 31
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)
Upvotes: 2
Reputation: 5588
// 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()
}
Upvotes: 0