Files
service-qgdzs/internal/dao/repository/records.go

68 lines
1.9 KiB
Go

package repository
import (
"context"
"git.hlsq.asia/mmorpg/service-common/db/mysql"
"git.hlsq.asia/mmorpg/service-common/db/redis"
"git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/model"
"git.hlsq.asia/mmorpg/service-qgdzs/internal/dao/query"
"time"
)
type RecordDao struct {
ctx context.Context
query *query.Query
cache *redis.CacheClient
}
func NewRecordDao(ctx context.Context, cache ...*redis.CacheClient) *RecordDao {
dao := &RecordDao{
ctx: ctx,
query: query.Use(mysql.GetDB(dbName)),
}
if len(cache) > 0 {
dao.cache = cache[0]
}
return dao
}
func (d *RecordDao) Create(record *model.Record) (*model.Record, error) {
err := d.query.Record.WithContext(d.ctx).
Create(record)
return record, err
}
type RecordItem struct {
QuestionSn string `gorm:"column:question_sn"`
Question string `gorm:"column:question"`
Difficulty int32 `gorm:"column:difficulty"`
Category string `gorm:"column:category"`
IsCorrect int32 `gorm:"column:is_correct"`
QuestionAnswer string `gorm:"column:question_answer"`
Answer string `gorm:"column:answer"`
CreatedAt time.Time `gorm:"column:created_at"`
}
func (d *RecordDao) FindByUSN(usn string, page, pageSize int) ([]*RecordItem, int64, error) {
result := make([]*RecordItem, 0)
count, err := d.query.Record.WithContext(d.ctx).
Select(
d.query.Question.Sn.As("question_sn"),
d.query.Question.Question,
d.query.Question.Difficulty,
d.query.Question.Answer.As("question_answer"),
d.query.Category.Category,
d.query.Record.Answer,
d.query.Record.CreatedAt,
).
Where(d.query.Record.UserSn.Eq(usn)).
LeftJoin(d.query.Question, d.query.Question.Sn.EqCol(d.query.Record.QuestionSn)).
LeftJoin(d.query.Category, d.query.Category.Sn.EqCol(d.query.Question.CategorySn)).
Order(d.query.Record.CreatedAt.Desc()).
ScanByPage(&result, (page-1)*pageSize, pageSize)
if err != nil {
return nil, 0, err
}
return result, count, nil
}