61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package person
|
|
|
|
import (
|
|
"log"
|
|
|
|
group "example.com/database/group"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Person struct {
|
|
gorm.Model
|
|
Name string `gorm:"primaryKey" json:"name"`
|
|
Groups []group.Group `gorm:"many2many:person_group_associations" json:"groups"` // Unique
|
|
}
|
|
|
|
func CreateDatabasePerson(db *gorm.DB, person Person) error {
|
|
result := db.Create(&person)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GetDatabasePerson(db *gorm.DB, inputPerson string) Person {
|
|
var outputPerson Person
|
|
result := db.Model(&Person{}).Where("name = ?", inputPerson).Take(&outputPerson)
|
|
if result.Error != nil {
|
|
return Person{}
|
|
}
|
|
db.Model(&outputPerson).Association("Groups").Find(&outputPerson.Groups)
|
|
return outputPerson
|
|
}
|
|
|
|
func GetDatabasePersons(db *gorm.DB, inputPersons []string) []Person {
|
|
var outputPersons []Person
|
|
for _, inputPerson := range inputPersons {
|
|
outputPersons = append(outputPersons, GetDatabasePerson(db, inputPerson))
|
|
}
|
|
return outputPersons
|
|
}
|
|
|
|
func GetAllDatabasePersons(db *gorm.DB) []Person {
|
|
var outputPersons []Person
|
|
result := db.Find(&outputPersons)
|
|
if result.Error != nil {
|
|
log.Println(result.Error)
|
|
}
|
|
for index, outputPerson := range outputPersons {
|
|
outputPersons[index] = GetDatabasePerson(db, outputPerson.Name)
|
|
}
|
|
return outputPersons
|
|
}
|
|
|
|
func UpdateDatabasePerson(db *gorm.DB, person Person) error {
|
|
result := db.Save(&person)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
return nil
|
|
}
|