82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
package repositories
|
|
|
|
import (
|
|
"learnsteam/cslms-api/internal/models"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type quizRepository struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
func NewQuizRepository(db *gorm.DB) QuizRepository {
|
|
return &quizRepository{
|
|
DB: db,
|
|
}
|
|
}
|
|
|
|
type QuizRepository interface {
|
|
List(int64, int, int) (*[]models.Quiz, error)
|
|
Total(int64) (int64, error)
|
|
|
|
Find(int64) (*models.Quiz, error)
|
|
Create(*models.Quiz) (*models.Quiz, error)
|
|
Update(*models.Quiz) (*models.Quiz, error)
|
|
Delete(int64) error
|
|
}
|
|
|
|
func (r *quizRepository) List(quiz_paper_id int64, page int, limit int) (*[]models.Quiz, error) {
|
|
var quizzes *[]models.Quiz
|
|
var err error
|
|
offset := limit * (page - 1)
|
|
if quiz_paper_id > 0 {
|
|
err = r.DB.Offset(offset).Limit(limit).Order("vol_no ASC").Where("quiz_paper_id = ?", quiz_paper_id).Find(&quizzes).Error
|
|
} else {
|
|
err = r.DB.Offset(offset).Limit(limit).Find(&quizzes).Error
|
|
}
|
|
return quizzes, err
|
|
}
|
|
|
|
func (r *quizRepository) Total(quiz_paper_id int64) (int64, error) {
|
|
var total int64
|
|
var err error
|
|
if quiz_paper_id > 0 {
|
|
err = r.DB.Model(&models.Quiz{}).Where("quiz_paper_id = ?", quiz_paper_id).Count(&total).Error
|
|
} else {
|
|
err = r.DB.Model(&models.Quiz{}).Count(&total).Error
|
|
}
|
|
|
|
return total, err
|
|
}
|
|
|
|
func (r *quizRepository) Find(id int64) (*models.Quiz, error) {
|
|
var quiz *models.Quiz
|
|
err := r.DB.Where("id = ?", id).First(&quiz).Error
|
|
return quiz, err
|
|
}
|
|
|
|
func (r *quizRepository) Create(quiz *models.Quiz) (*models.Quiz, error) {
|
|
err := r.DB.Create(&quiz).Error
|
|
return quiz, err
|
|
}
|
|
|
|
func (r *quizRepository) Update(quiz *models.Quiz) (*models.Quiz, error) {
|
|
var row *models.Quiz
|
|
if err := r.DB.Where("id=?", quiz.ID).First(&row).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err := r.DB.Model(&row).Select("*").Updates(&quiz).Error
|
|
return row, err
|
|
}
|
|
|
|
func (r *quizRepository) Delete(id int64) error {
|
|
var quiz *models.Quiz
|
|
if err := r.DB.Where("id=?", id).First(&quiz).Error; err != nil {
|
|
return err
|
|
}
|
|
err := r.DB.Delete(&quiz).Error
|
|
return err
|
|
}
|