94 lines
2.5 KiB
Go
94 lines
2.5 KiB
Go
package inventoryslot
|
|
|
|
import (
|
|
"log"
|
|
|
|
item "example.com/database/item"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type InventorySlot struct {
|
|
gorm.Model
|
|
Item item.Item `gorm:"foreignKey:Name" json:"item"`
|
|
Quantity int64 `json:"quantity"` // Positive
|
|
}
|
|
|
|
func (inventorySlot InventorySlot) Create(db *gorm.DB) error {
|
|
result := db.Create(&inventorySlot)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (inventorySlot *InventorySlot) getAssociations(db *gorm.DB) {
|
|
db.Model(&inventorySlot).Association("Item").Find(&inventorySlot.Item)
|
|
|
|
}
|
|
|
|
func (inventorySlot *InventorySlot) Get(db *gorm.DB, inputInventorySlot uint) {
|
|
db.Where("id = ?", inputInventorySlot).Take(&inventorySlot)
|
|
inventorySlot.getAssociations(db)
|
|
}
|
|
|
|
func (inventorySlot InventorySlot) Update(db *gorm.DB) error {
|
|
var originalIventorySlot InventorySlot
|
|
originalIventorySlot.Get(db, inventorySlot.ID)
|
|
itemsError := db.Model(&originalIventorySlot).Association("Item").Replace(&inventorySlot.Item)
|
|
if itemsError != nil {
|
|
return itemsError
|
|
}
|
|
originalIventorySlot.Quantity = inventorySlot.Quantity
|
|
return nil
|
|
}
|
|
|
|
func (inventorySlot InventorySlot) Delete(db *gorm.DB) error {
|
|
result := db.Delete(&inventorySlot)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Create(db *gorm.DB, itemName string, quantity int64) error {
|
|
return InventorySlot{
|
|
Item: (*item.Get(db, []string{itemName}))[0],
|
|
Quantity: quantity,
|
|
}.Create(db)
|
|
}
|
|
|
|
func Get(db *gorm.DB, inputInventorySlots []uint) *[]InventorySlot {
|
|
var outputInventorySlots []InventorySlot
|
|
for _, inputInventorySlot := range inputInventorySlots {
|
|
var outputInventorySlot InventorySlot
|
|
outputInventorySlot.Get(db, inputInventorySlot)
|
|
outputInventorySlots = append(outputInventorySlots, outputInventorySlot)
|
|
}
|
|
return &outputInventorySlots
|
|
}
|
|
|
|
func GetAll(db *gorm.DB) *[]InventorySlot {
|
|
var outputInventorySlotIDs []uint
|
|
result := db.Model(&InventorySlot{}).Select("id").Find(&outputInventorySlotIDs)
|
|
if result.Error != nil {
|
|
log.Println(result.Error)
|
|
}
|
|
return Get(db, outputInventorySlotIDs)
|
|
}
|
|
|
|
func Update(db *gorm.DB, itemID int, itemName string, quantity int64) error {
|
|
inventorySlot := InventorySlot{
|
|
Item: (*item.Get(db, []string{itemName}))[0],
|
|
Quantity: quantity,
|
|
}
|
|
inventorySlot.ID = uint(itemID)
|
|
return inventorySlot.Update(db)
|
|
}
|
|
|
|
func Delete(db *gorm.DB, inputInventorySlotIDs []uint) {
|
|
inventorySlots := Get(db, inputInventorySlotIDs)
|
|
for _, inventorySlot := range *inventorySlots {
|
|
inventorySlot.Delete(db)
|
|
}
|
|
}
|