[英]Firestore - Query multiple fields
我正在尋找使用 Flutter + Firestore 構建一個簡單的聊天應用程序,將用戶和聊天存儲在單獨的 collections 中。 每個聊天文檔都有兩個字符串字段 [uid1, uid2] 代表各個參與者的用戶 ID。 我需要能夠搜索給定用戶 (uid) 的所有聊天記錄,因此可以進行某種類型的 OR 查詢,這可以通過將它們存儲在數組字段中並使用 array_contains 來實現。
但是,要更新聊天文檔,我需要能夠直接查詢兩個字段以檢索兩個用戶之間的特定聊天,而使用數組方法是不可能的(不允許嵌套 array_contains)。 即使將兩者都存儲為兩個頂級字符串字段,也需要針對任一方向進行兩次 Firestore 查詢。
感謝有關如何解決 Firestore 查詢限制的任何建議?
您可以通過將兩個用戶 ID 連接到一個字符串中來創建一個包含查詢所需的所有數據的復合字段。 請務必在這樣做之前對 ID 進行排序,以確保它們具有可預測的順序。
因此,如果您有用戶“A”和用戶“B”,您的復合字段值將只是“AB”(而不是“BA”),您可以過濾此字段以查找這兩個用戶之間的所有消息。
很抱歉我的簡短解釋,我只是找個合適的時間分享我的經驗,所以我有點搞砸了,所以我希望稍后我會更新我的帖子,謝謝你的理解。
我的留言 Model,
class Message {
final DateTime time;
final String text;
final Map<String, dynamic> toFromUser;
Message({
required this.toFromUser,
required this.time,
required this.text,
});
Map<String, dynamic> getDataMap() {
return {
"toFromUser": toFromUser,
"time": time,
"text": text,
};
}
}
我這樣發送,
Message message = Message(
toFromUser: {
"from": Auth().currentUserId(),
"to": toUserId
},
time: DateTime.now(),
text: messageText.text,
);
我的 Stream Builder 像這樣,widget.userData.id 是其他用戶 B。A 是我,B 是朋友。 :)
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('messages')
.where("toFromUser", whereIn: [ // index is used to use both where and orderBy.
{"to": widget.userData.id, "from": Auth().currentUserId()},
{"to": Auth().currentUserId(), "from": widget.userData.id}
])
.orderBy('time')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
print(widget.userData.id);
return const Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Text("Loading");
}
// TODO: move list to bottom when new message is sent
return ListView(
padding: const EdgeInsets.all(20),
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
Message message = Message(
toFromUser: data["toFromUser"],
time: (data['time'] as Timestamp).toDate(),
text: data["text"],
);
final bool isMe =
data["toFromUser"]["from"] == Auth().currentUserId();
return chatBubble(context, message, isMe);
}).toList(),
);
},
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.