fix(service): 仅返回活跃会话中的聊天角色列表
This commit is contained in:
@@ -79,14 +79,31 @@ public class KeyboardAiChatMessageServiceImpl extends ServiceImpl<KeyboardAiChat
|
||||
|
||||
@Override
|
||||
public List<Long> getChattedCompanionIds(Long userId) {
|
||||
// 使用原生SQL查询用户聊过天的所有角色ID,按最近聊天时间倒序
|
||||
// 1. 查询用户所有活跃会话
|
||||
LambdaQueryWrapper<KeyboardAiChatSession> sessionWrapper = new LambdaQueryWrapper<>();
|
||||
sessionWrapper.eq(KeyboardAiChatSession::getUserId, userId)
|
||||
.eq(KeyboardAiChatSession::getIsActive, true);
|
||||
List<KeyboardAiChatSession> activeSessions = sessionService.list(sessionWrapper);
|
||||
|
||||
// 2. 如果没有活跃会话,返回空列表
|
||||
if (activeSessions == null || activeSessions.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// 3. 提取活跃会话的 sessionId 列表
|
||||
List<Long> activeSessionIds = activeSessions.stream()
|
||||
.map(KeyboardAiChatSession::getId)
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
|
||||
// 4. 查询这些会话中的消息,获取 companionId,按最近聊天时间倒序
|
||||
LambdaQueryWrapper<KeyboardAiChatMessage> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(KeyboardAiChatMessage::getUserId, userId)
|
||||
.select(KeyboardAiChatMessage::getCompanionId)
|
||||
.groupBy(KeyboardAiChatMessage::getCompanionId)
|
||||
.orderByDesc(KeyboardAiChatMessage::getCompanionId);
|
||||
.in(KeyboardAiChatMessage::getSessionId, activeSessionIds)
|
||||
.orderByDesc(KeyboardAiChatMessage::getCreatedAt);
|
||||
|
||||
List<KeyboardAiChatMessage> messages = this.list(queryWrapper);
|
||||
|
||||
// 5. 去重并保持顺序(按最近聊天时间)
|
||||
return messages.stream()
|
||||
.map(KeyboardAiChatMessage::getCompanionId)
|
||||
.distinct()
|
||||
|
||||
Reference in New Issue
Block a user