cslms-api/internal/repositories/center.go

90 lines
2.3 KiB
Go
Raw Normal View History

2023-12-27 17:31:49 +09:00
package repositories
import (
"fmt"
"learnsteam/cslms-api/internal/models"
"gorm.io/gorm"
)
type centerRepository struct {
DB *gorm.DB
}
func NewCenterRepository(db *gorm.DB) CenterRepository {
return &centerRepository{
DB: db,
}
}
type CenterRepository interface {
List(string, int, int) (*[]models.Center, error)
Total(string) (int64, error)
Find(int64) (*models.Center, error)
FindByTitle(string) (*models.Center, error)
Create(*models.Center) (*models.Center, error)
Update(*models.Center) (*models.Center, error)
Delete(int64) error
}
func (r *centerRepository) List(q string, page int, limit int) (*[]models.Center, error) {
var centers *[]models.Center
var err error
offset := limit * (page - 1)
fmt.Println("q", q)
if q != "" {
err = r.DB.Offset(offset).Limit(limit).Order("center_title ASC").Where("center_title LIKE ? OR center_name LIKE ?", "%"+q+"%", "%"+q+"%").Find(&centers).Error
} else {
err = r.DB.Offset(offset).Limit(limit).Order("center_title ASC").Find(&centers).Error
}
return centers, err
}
func (r *centerRepository) Total(q string) (int64, error) {
var total int64
var err error
if q != "" {
err = r.DB.Model(&models.Center{}).Where("center_title LIKE ? OR center_name LIKE ?", "%"+q+"%", "%"+q+"%").Count(&total).Error
} else {
err = r.DB.Model(&models.Center{}).Count(&total).Error
}
return total, err
}
func (r *centerRepository) Find(id int64) (*models.Center, error) {
var center *models.Center
err := r.DB.Where("id = ?", id).First(&center).Error
return center, err
}
func (r *centerRepository) FindByTitle(center_title string) (*models.Center, error) {
var center *models.Center
err := r.DB.Where("center_title = ?", center_title).First(&center).Error
return center, err
}
func (r *centerRepository) Create(center *models.Center) (*models.Center, error) {
err := r.DB.Create(&center).Error
return center, err
}
func (r *centerRepository) Update(center *models.Center) (*models.Center, error) {
var row *models.Center
if err := r.DB.Where("id=?", center.ID).First(&row).Error; err != nil {
return nil, err
}
err := r.DB.Model(&row).Select("*").Updates(&center).Error
return row, err
}
func (r *centerRepository) Delete(id int64) error {
var center *models.Center
if err := r.DB.Where("id=?", id).First(&center).Error; err != nil {
return err
}
err := r.DB.Delete(&center).Error
return err
}