Reputation: 231
I am trying to add an OR
condition to my flutter firebase query.
Here is my code but I want to check where receiver_name
is equal to kim
OR sender_name
is equal to kim
StreamBuilder(
stream: Firestore.instance.collection("payments").where("receiver_name", isEqualTo: userActive).snapshots(),
builder: (context, snapshot){
return Container ( child:ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
padding: EdgeInsets.all(0),
controller: ScrollController(keepScrollOffset: false),
itemBuilder: (context, index){
DocumentSnapshot documentSnapshot = snapshot.data.documents[index];
Upvotes: 6
Views: 4859
Reputation: 598797
Update: Since March 2023 OR conditions across multiple fields are possible on Firestore, as shown in the new documentation on OR
queries. Be sure to check out the document, including the limitations on queries that use OR clauses.
An example of the syntax for OR conditions:
snapshot = await db.collection('/76015089').where(
Filter.or(
Filter("name", isEqualTo: "John"),
Filter("id", isNotEqualTo: "null"),
)
).get();
print('Got ${snapshot.docs.length} documents');
for (var doc in snapshot.docs) {
print(' ${doc.id}: name=${doc.get("name")} id=${doc.get("id")}');
}
For this specific use-case, you can also consider this alternative solution:
If you add an array field participants
to your documents, with in it the UID fields of the sender and the receiver, you can then use an array-contains
query to get all payments in which the user was either the sender or the receiver.
To add a UID to such an array, be sure to use the array-union
operator:
documentRef.updateData({"participants": FieldValue.arrayUnion("uidOfUser")});
And then to query it, you'd use:
collectionRef.where('participants', arrayContains: "uidOfUser")
Upvotes: 6
Reputation: 467
OR operator is now available in Firebase.
Its can be achieved now by using Filter.or
.
Follow this link for more details on it: OR operator
For this you need Cloud Firestore version 24.4.5
in Flutter you need cloud_firestore: ^4.5.0
To query it, you have write like this:
Firestore.instance.collection("payments")
.where(Filter.or(
Filter("receiver_name", isEqualTo: "kim"),
Filter("sender_name", isEqualTo: "kim")
)).snapshots();
Upvotes: 9