2024-07-19 19:04:11 +08:00
|
|
|
package repo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"gorm.io/gorm"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DBOption func(*gorm.DB) *gorm.DB
|
|
|
|
|
|
|
|
type ICommonRepo interface {
|
2024-07-25 14:43:41 +08:00
|
|
|
WithByID(id uint) DBOption
|
2024-08-08 15:38:37 +08:00
|
|
|
WithByName(name string) DBOption
|
2024-08-13 15:33:34 +08:00
|
|
|
WithByIDs(ids []uint) DBOption
|
2024-08-08 15:38:37 +08:00
|
|
|
WithByType(ty string) DBOption
|
2024-07-19 19:04:11 +08:00
|
|
|
WithOrderBy(orderStr string) DBOption
|
|
|
|
}
|
|
|
|
|
|
|
|
type CommonRepo struct{}
|
|
|
|
|
2024-07-25 14:43:41 +08:00
|
|
|
func NewICommonRepo() ICommonRepo {
|
2024-07-19 19:04:11 +08:00
|
|
|
return &CommonRepo{}
|
|
|
|
}
|
2024-07-25 14:43:41 +08:00
|
|
|
|
|
|
|
func (c *CommonRepo) WithByID(id uint) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("id = ?", id)
|
|
|
|
}
|
|
|
|
}
|
2024-08-08 15:38:37 +08:00
|
|
|
func (c *CommonRepo) WithByName(name string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
if len(name) == 0 {
|
|
|
|
return g
|
|
|
|
}
|
|
|
|
return g.Where("`name` = ?", name)
|
|
|
|
}
|
|
|
|
}
|
2024-08-13 15:33:34 +08:00
|
|
|
func (c *CommonRepo) WithByIDs(ids []uint) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Where("id in (?)", ids)
|
|
|
|
}
|
|
|
|
}
|
2024-08-08 15:38:37 +08:00
|
|
|
func (c *CommonRepo) WithByType(ty string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
if len(ty) == 0 {
|
|
|
|
return g
|
|
|
|
}
|
|
|
|
return g.Where("`type` = ?", ty)
|
|
|
|
}
|
|
|
|
}
|
2024-07-19 19:04:11 +08:00
|
|
|
func (c *CommonRepo) WithOrderBy(orderStr string) DBOption {
|
|
|
|
return func(g *gorm.DB) *gorm.DB {
|
|
|
|
return g.Order(orderStr)
|
|
|
|
}
|
|
|
|
}
|