fixed gorm shema for correct deletion and many2many relation beetween users and devices

This commit is contained in:
tdv
2025-09-15 16:59:35 +03:00
parent 673971deb8
commit aa60651610
5 changed files with 17 additions and 5 deletions

View File

@@ -16,5 +16,6 @@ func AutoMigrate(db *gorm.DB) error {
&models.User{},
&models.Device{},
&models.Record{},
&models.UserDevice{},
)
}

View File

@@ -106,12 +106,10 @@ func (h *UsersHandler) Delete(c *gin.Context) {
return
}
var u models.User
if err := h.db.Preload("Devices").First(&u, id).Error; err != nil {
if err := h.db.First(&u, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
// optional safeguard: prevent self-delete; uncomment if desired
// if ClaimUserID(MustClaims(c)) == u.ID { c.JSON(http.StatusBadRequest, gin.H{"error":"cannot delete yourself"}); return }
if err := h.db.Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&u).Association("Devices").Clear(); err != nil {
return err

View File

@@ -5,7 +5,7 @@ import "time"
type Device struct {
GUID string `gorm:"primaryKey"`
Name string `gorm:"size:255;not null"`
Users []User `gorm:"many2many:user_devices;joinForeignKey:ID;joinReferences:GUID"`
Users []User `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
Records []Record `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
CreatedAt time.Time
UpdatedAt time.Time

View File

@@ -14,7 +14,7 @@ type User struct {
Username string `gorm:"uniqueIndex;size:255;not null"`
Password string `gorm:"not null"`
Role Role `gorm:"type:varchar(16);not null;default:'user'"`
Devices []Device `gorm:"many2many:user_devices;joinForeignKey:ID;joinReferences:GUID"`
Devices []Device `gorm:"many2many:user_devices;constraint:OnDelete:CASCADE;"`
CreatedAt time.Time
UpdatedAt time.Time
}

View File

@@ -0,0 +1,13 @@
package models
import "time"
type UserDevice struct {
UserID uint `gorm:"primaryKey;index;not null"`
DeviceGUID string `gorm:"primaryKey;size:64;index;not null"`
CreatedAt time.Time
// Optional FKs with cascade (you already have cascade constraints on both sides)
User User `gorm:"constraint:OnDelete:CASCADE;"`
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
}