45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
package models
|
|
|
|
import (
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Album struct {
|
|
ID uint32 `gorm:"primary_key" json:"id"`
|
|
Name string `gorm:"not null" json:"name"`
|
|
Fullname string `gorm:"-" json:"fullname"`
|
|
Parent *Album `gorm:"constraint:OnDelete:SET NULL,OnUpdate:CASCADE" json:"-"`
|
|
ParentId *uint32 `json:"parent_id"`
|
|
Author *Account `gorm:"constraint:OnDelete:SET NULL,OnUpdate:CASCADE" json:"author"`
|
|
AuthorId *uint32 `json:"-"`
|
|
Photos []*Photo `gorm:"many2many:album_photos" json:"-"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
func (a *Album) AfterFind(tx *gorm.DB) error {
|
|
a.ComputeFullpath(tx)
|
|
return nil
|
|
}
|
|
|
|
func (a *Album) AfterCreate(tx *gorm.DB) error {
|
|
a.ComputeFullpath(tx)
|
|
return nil
|
|
}
|
|
|
|
func (a *Album) ComputeFullpath(tx *gorm.DB) error {
|
|
if a.ParentId == nil {
|
|
a.Fullname = a.Name
|
|
} else {
|
|
parent := &Album{}
|
|
if err := tx.Session(&gorm.Session{NewDB: true}).Select("name", "parent_id").First(parent, "id = ?", a.ParentId).Error; err != nil {
|
|
return err
|
|
}
|
|
a.Fullname = filepath.Join(parent.Fullname, a.Name)
|
|
}
|
|
return nil
|
|
}
|