88 lines
1.9 KiB
Go
88 lines
1.9 KiB
Go
package dao
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"yintai-api/app/common/model"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Page struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewPage(db ...*gorm.DB) *Page {
|
|
return &Page{db: getDB(db...)}
|
|
}
|
|
|
|
func (r *Page) TableName() string {
|
|
return "yt_page"
|
|
}
|
|
|
|
func (r *Page) Create(m *model.Page) error {
|
|
return r.db.Table(r.TableName()).Create(m).Error
|
|
}
|
|
|
|
func (r *Page) Update(m *model.Page) error {
|
|
return r.db.Table(r.TableName()).Save(m).Error
|
|
}
|
|
|
|
func (r *Page) Delete(id int64) error {
|
|
return r.db.Table(r.TableName()).Where("id = ?", id).Delete(&Page{}).Error
|
|
}
|
|
|
|
func (r *Page) Get(id int64) (*model.Page, error) {
|
|
var res model.Page
|
|
if err := r.db.Table(r.TableName()).Where("id = ?", id).First(&res).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &res, nil
|
|
}
|
|
|
|
func (r *Page) Exists(id int64) (bool, error) {
|
|
var count int64
|
|
if err := r.db.Table(r.TableName()).Where("id = ?", id).Count(&count).Error; err != nil {
|
|
return false, err
|
|
}
|
|
return count > 0, nil
|
|
}
|
|
|
|
func (r *Page) List(name string, page, size int, sort string) ([]*model.Page, int64, error) {
|
|
var list []*model.Page
|
|
var count int64
|
|
tx := r.db.Table(r.TableName()).Where("name LIKE ?", fmt.Sprintf("%%%s%%", name))
|
|
if err := tx.Count(&count).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
if sort != "" {
|
|
tx = tx.Order(sort)
|
|
} else {
|
|
tx = tx.Order("id,pid,weight desc")
|
|
}
|
|
|
|
if err := tx.Offset((page - 1) * size).Limit(size).Find(&list).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, 0, err
|
|
}
|
|
return nil, 0, err
|
|
}
|
|
return list, count, nil
|
|
}
|
|
|
|
func (r *Page) GetByPath(path string) ([]*model.Page, error) {
|
|
var list []*model.Page
|
|
tx := r.db.Table(r.TableName()).Where("path LIKE ?", fmt.Sprintf("%s%%", path)).Find(&list)
|
|
if tx.Error != nil {
|
|
if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, tx.Error
|
|
}
|
|
return list, nil
|
|
}
|