2020-02-05 16:14:21 +01:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2020-11-25 23:06:47 +01:00
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
|
|
|
|
2020-11-23 19:59:01 +01:00
|
|
|
"gorm.io/gorm"
|
2020-02-05 16:14:21 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type Album struct {
|
2020-11-28 21:29:31 +01:00
|
|
|
Model
|
2020-11-28 21:49:33 +01:00
|
|
|
Title string `gorm:"not null"`
|
2021-01-19 17:31:37 +01:00
|
|
|
ParentAlbumID *int `gorm:"index"`
|
2021-01-06 17:28:06 +01:00
|
|
|
ParentAlbum *Album `gorm:"constraint:OnDelete:SET NULL;"`
|
2020-12-22 01:14:43 +01:00
|
|
|
// OwnerID int `gorm:"not null"`
|
|
|
|
// Owner User
|
|
|
|
Owners []User `gorm:"many2many:user_albums"`
|
|
|
|
Path string `gorm:"not null"`
|
|
|
|
PathHash string `gorm:"unique"`
|
2020-02-05 16:14:21 +01:00
|
|
|
}
|
|
|
|
|
2020-03-07 16:19:27 +01:00
|
|
|
func (a *Album) FilePath() string {
|
|
|
|
return a.Path
|
|
|
|
}
|
2020-11-25 23:06:47 +01:00
|
|
|
|
|
|
|
func (a *Album) BeforeSave(tx *gorm.DB) (err error) {
|
|
|
|
hash := md5.Sum([]byte(a.Path))
|
|
|
|
a.PathHash = hex.EncodeToString(hash[:])
|
|
|
|
return nil
|
|
|
|
}
|
2020-12-31 00:37:11 +01:00
|
|
|
|
2021-03-03 15:55:55 +01:00
|
|
|
// GetChildren performs a recursive query to get all the children of the album.
|
|
|
|
// An optional filter can be provided that can be used to modify the query on the children.
|
|
|
|
func (a *Album) GetChildren(db *gorm.DB, filter func(*gorm.DB) *gorm.DB) (children []*Album, err error) {
|
|
|
|
// SELECT * FROM sub_albums
|
|
|
|
query := db.Model(&Album{}).Table("sub_albums")
|
|
|
|
|
|
|
|
if filter != nil {
|
|
|
|
query = filter(query)
|
|
|
|
}
|
|
|
|
|
2020-12-31 00:37:11 +01:00
|
|
|
err = db.Raw(`
|
|
|
|
WITH recursive sub_albums AS (
|
|
|
|
SELECT * FROM albums AS root WHERE id = ?
|
|
|
|
UNION ALL
|
|
|
|
SELECT child.* FROM albums AS child JOIN sub_albums ON child.parent_album_id = sub_albums.id
|
|
|
|
)
|
|
|
|
|
2021-03-03 15:55:55 +01:00
|
|
|
?
|
|
|
|
`, a.ID, query).Find(&children).Error
|
2020-12-31 00:37:11 +01:00
|
|
|
|
|
|
|
return children, err
|
|
|
|
}
|