You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:22:04