You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.8 KiB
65 lines
1.8 KiB
package model
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// AIConversationInsert 插入AI对话
|
|
func AIConversationInsert(ctx context.Context, db *gorm.DB, conversation *AIConversation) (int64, error) {
|
|
result := db.WithContext(ctx).Create(conversation)
|
|
if result.Error != nil {
|
|
return 0, result.Error
|
|
}
|
|
return conversation.Id, nil
|
|
}
|
|
|
|
// AIConversationFindOne 根据ID查询AI对话
|
|
func AIConversationFindOne(ctx context.Context, db *gorm.DB, id int64) (*AIConversation, error) {
|
|
var conversation AIConversation
|
|
result := db.WithContext(ctx).First(&conversation, id)
|
|
if result.Error != nil {
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, result.Error
|
|
}
|
|
return &conversation, nil
|
|
}
|
|
|
|
// AIConversationUpdate 更新AI对话
|
|
func AIConversationUpdate(ctx context.Context, db *gorm.DB, conversation *AIConversation) error {
|
|
result := db.WithContext(ctx).Save(conversation)
|
|
return result.Error
|
|
}
|
|
|
|
// AIConversationDelete 删除AI对话
|
|
func AIConversationDelete(ctx context.Context, db *gorm.DB, id int64) error {
|
|
result := db.WithContext(ctx).Delete(&AIConversation{}, id)
|
|
return result.Error
|
|
}
|
|
|
|
// AIConversationFindByUser 根据用户ID查询对话列表(分页,按更新时间倒序)
|
|
func AIConversationFindByUser(ctx context.Context, db *gorm.DB, userId int64, page, pageSize int64) ([]AIConversation, int64, error) {
|
|
var conversations []AIConversation
|
|
var total int64
|
|
|
|
query := db.WithContext(ctx).Model(&AIConversation{}).Where("user_id = ?", userId)
|
|
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
offset := (page - 1) * pageSize
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
err := query.Order("updated_at DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&conversations).Error
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return conversations, total, nil
|
|
}
|
|
|