49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package models
|
|
|
|
import (
|
|
"GoMembership/pkg/logger"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Category struct {
|
|
ID uint `json:"id" gorm:"primaryKey"`
|
|
Name string `json:"category" binding:"safe_content"`
|
|
}
|
|
|
|
func (c *Category) Create(db *gorm.DB) error {
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
// Create the base User record (omit associations to handle them separately)
|
|
if err := tx.Create(c).Error; err != nil {
|
|
return err
|
|
}
|
|
logger.Info.Printf("Category created: %#v", c)
|
|
// Preload all associations to return the fully populated User
|
|
return tx.
|
|
First(c, c.ID).Error // Refresh the user object with all associations
|
|
})
|
|
}
|
|
|
|
func (c *Category) Update(db *gorm.DB) error {
|
|
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
// Check if the user exists in the database
|
|
var existingCategory Category
|
|
|
|
logger.Info.Printf("updating Category: %#v", c)
|
|
if err := tx.First(&existingCategory, c.ID).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := tx.Model(&existingCategory).Updates(c).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.First(c, c.ID).Error
|
|
})
|
|
|
|
}
|
|
|
|
func (c *Category) Delete(db *gorm.DB) error {
|
|
return db.Delete(&c).Error
|
|
}
|