Firestore中如何在同一查询中多次使用whereEqualTo?
解决Firestore聊天消息双向查询问题
你当前的查询仅筛选了当前用户发送给对方的消息(fromId = 当前用户ID 且 toId = 对方用户ID),所以只能看到单向内容。要获取双方互发的所有消息,需要用whereOr组合两组条件:
- 当前用户发给对方:
fromId = currentUser.userId且toId = otherUser.userId - 对方发给当前用户:
fromId = otherUser.userId且toId = currentUser.userId
修正后的Kotlin查询代码
val db = FirebaseFirestore.getInstance() val messagesRef = db.collection("messages") val query = messagesRef .whereOr( // 条件1:当前用户发对方的消息 Filter.and( Filter.equalTo("fromId", currentUser.userId), Filter.equalTo("toId", otherUser.userId) ), // 条件2:对方发当前用户的消息 Filter.and( Filter.equalTo("fromId", otherUser.userId), Filter.equalTo("toId", currentUser.userId) ) ) .orderBy("createdAt", Query.Direction.ASCENDING)
补充说明
- 该查询会返回双方之间的所有对话消息,无论发送方是谁,最终按消息发送时间升序排列。
- 首次运行查询时,Firestore控制台会提示创建对应的复合索引,直接根据提示链接完成索引创建即可,否则查询会报错。
内容的提问来源于stack exchange,提问作者Divyansh Singh
相关产品推荐
相关产品推荐

