fixed gorm shema for correct deletion and many2many relation beetween users and devices
This commit is contained in:
@@ -16,5 +16,6 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&models.User{},
|
||||
&models.Device{},
|
||||
&models.Record{},
|
||||
&models.UserDevice{},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
13
server/internal/models/user_device.go
Normal file
13
server/internal/models/user_device.go
Normal 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"`
|
||||
}
|
||||
Reference in New Issue
Block a user