cslms-api/internal/repositories/userquizpaper.go
2023-12-29 00:27:12 +09:00

89 lines
2.7 KiB
Go

package repositories
import (
"learnsteam/cslms-api/internal/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type userQuizPaperRepository struct {
DB *gorm.DB
}
func NewUserQuizPaperRepository(db *gorm.DB) UserQuizPaperRepository {
return &userQuizPaperRepository{
DB: db,
}
}
type UserQuizPaperRepository interface {
List(string, int, int) (*[]models.UserQuizPaper, error)
Total(string) (int64, error)
Find(int64) (*models.UserQuizPaper, error)
Create(*models.UserQuizPaper) (*models.UserQuizPaper, error)
Insert([]models.UserQuizPaper) ([]models.UserQuizPaper, error)
Update(*models.UserQuizPaper) (*models.UserQuizPaper, error)
Delete(string) error
}
func (r *userQuizPaperRepository) List(q string, page int, limit int) (*[]models.UserQuizPaper, error) {
var userQuizPapers *[]models.UserQuizPaper
var err error
offset := limit * (page - 1)
if q != "" {
err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Where("subject LIKE ? OR program LIKE ? OR name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Find(&userQuizPapers).Error
} else {
err = r.DB.Offset(offset).Limit(limit).Order("created_at DESC").Find(&userQuizPapers).Error
}
return userQuizPapers, err
}
func (r *userQuizPaperRepository) Total(q string) (int64, error) {
var total int64
var err error
if q != "" {
err = r.DB.Model(&models.UserQuizPaper{}).Where("subject LIKE ? OR program LIKE ? OR name LIKE ?", "%"+q+"%", "%"+q+"%", "%"+q+"%").Count(&total).Error
} else {
err = r.DB.Model(&models.UserQuizPaper{}).Count(&total).Error
}
return total, err
}
func (r *userQuizPaperRepository) Find(id int64) (*models.UserQuizPaper, error) {
var userQuizPaper *models.UserQuizPaper
err := r.DB.Where("id = ?", id).First(&userQuizPaper).Error
return userQuizPaper, err
}
func (r *userQuizPaperRepository) Create(userQuizPaper *models.UserQuizPaper) (*models.UserQuizPaper, error) {
err := r.DB.Create(&userQuizPaper).Error
return userQuizPaper, err
}
func (r *userQuizPaperRepository) Insert(items []models.UserQuizPaper) ([]models.UserQuizPaper, error) {
err := r.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&items).Error
return items, err
}
func (r *userQuizPaperRepository) Update(userQuizPaper *models.UserQuizPaper) (*models.UserQuizPaper, error) {
var row *models.UserQuizPaper
if err := r.DB.Where("id=?", userQuizPaper.ID).First(&row).Error; err != nil {
return nil, err
}
err := r.DB.Model(&row).Select("*").Updates(&userQuizPaper).Error
return row, err
}
func (r *userQuizPaperRepository) Delete(id string) error {
var userQuizPaper *models.UserQuizPaper
if err := r.DB.Where("id=?", id).First(&userQuizPaper).Error; err != nil {
return err
}
err := r.DB.Delete(&userQuizPaper).Error
return err
}