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 ¢erRepository{ 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(¢ers).Error } else { err = r.DB.Offset(offset).Limit(limit).Order("center_title ASC").Find(¢ers).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(¢er).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(¢er).Error return center, err } func (r *centerRepository) Create(center *models.Center) (*models.Center, error) { err := r.DB.Create(¢er).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(¢er).Error return row, err } func (r *centerRepository) Delete(id int64) error { var center *models.Center if err := r.DB.Where("id=?", id).First(¢er).Error; err != nil { return err } err := r.DB.Delete(¢er).Error return err }