Decrement likes counters on user delete

This commit is contained in:
Thomas Miceli 2023-03-14 17:05:21 +01:00
parent bee5d045c3
commit 8630f647c6
No known key found for this signature in database
GPG key ID: D86C6F6390AF050F

View file

@ -1,5 +1,7 @@
package models package models
import "gorm.io/gorm"
type User struct { type User struct {
ID uint `gorm:"primaryKey"` ID uint `gorm:"primaryKey"`
Username string `form:"username" gorm:"uniqueIndex" validate:"required,max=24,alphanum,notreserved"` Username string `form:"username" gorm:"uniqueIndex" validate:"required,max=24,alphanum,notreserved"`
@ -46,6 +48,21 @@ func CreateUser(user *User) error {
} }
func DeleteUserByID(userid string) error { func DeleteUserByID(userid string) error {
// Decrement likes counter for all gists liked by this user
// The likes will be automatically deleted by the foreign key constraint
err := db.Model(&Gist{}).
Omit("updated_at").
Where("id IN (?)", db.
Select("gist_id").
Table("likes").
Where("user_id = ?", userid),
).
UpdateColumn("nb_likes", gorm.Expr("nb_likes - 1")).
Error
if err != nil {
return err
}
return db.Delete(&User{}, "id = ?", userid).Error return db.Delete(&User{}, "id = ?", userid).Error
} }