[英]Separate Queries Instead Multiple Where Clause in Firestore
I want to query firebase firestore data collection with two paramaters. 我想用两个参数查询Firebase Firestore数据集合。
The collection: animals 集合:动物
"animals": {
"1": {
"animal1": "cat",
"animal2": "dog",
"animal3": "",
"animal4": ""
},
"2": {
"animal1": "dog",
"animal2": "cat",
"animal3": "",
"animal4": ""
},
"3": {
"animal1": "cat",
"animal2": "bird",
"animal3": "dog",
"animal4": ""
},
"4": {
"animal1": "wolf",
"animal2": "dog",
"animal3": "bird",
"animal4": ""
},
"5": {
"animal1": "turtle",
"animal2": "dog",
"animal3": "wolf",
"animal4": "cat"
},
"6": {
"animal1": "dog",
"animal2": "wolf",
"animal3": "turtle",
"animal4": "bear"
},
"7": {
"animal1": "spider",
"animal2": "beatle",
"animal3": "butterfly",
"animal4": "Cat"
}
}
I want getting list datas that include cat and dog . 我想获取包括cat和dog的列表数据。 There is information In here Logical OR queries. 有信息在这里 逻辑或查询。 In this case, you should create a separate query for each OR condition and merge the query results in your app. 在这种情况下,您应该为每个OR条件创建一个单独的查询,并将查询结果合并到您的应用中。
I don't know how many separate query I need? 我不知道我需要多少个单独的查询?
let param1 = 'cat';
let param2 = 'dog';
let query1 = db.collection('animals').where('animal1', '==', param1);
let query2 = db.collection('animals').where('animal2', '==', param1);
let query3 = db.collection('animals').where('animal3', '==', param2);
let query4 = db.collection('animals').where('animal4', '==', param3);
As you have noted "you should create a separate query for each OR condition and merge the query results in your app". 如前所述,“您应该为每个OR条件创建一个单独的查询,并将查询结果合并到您的应用中”。 Since, with your data model, you have 4 fields ( animal1
to animal4
) you will need to create 4 queries for each param
value you want to test for. 由于使用数据模型,您有4个字段( animal1
到animal4
),因此需要为要测试的每个param
值创建4个查询。
So in case of 2 params, as follows: 因此,在2个参数的情况下,如下所示:
let param1 = 'cat';
let param2 = 'dog';
you will have to merge the results of 2*4 queries.... 您将必须合并2 * 4查询的结果...。
There is a possibility to decrease this number if you change your data model and use an array for storing the animal
values. 如果更改数据模型并使用数组存储animal
值,则有可能减少此数字。 You could then take advantage of the array_contains
operator. 然后,您可以利用array_contains
运算符。
Proposed data model: 建议的数据模型:
"animals": {
"1": {
"animalArray":
[
0: "cat",
1: "dog"
]
},
"2": {
"animalArray":
[
0: "turtle",
1: "dog",
2: "wolf",
3: "bear",
]
}
.....
}
With our example of two params
, you would need two queries only, as follows: 在我们的两个params
示例中,您仅需要两个查询,如下所示:
let query1 = db.collection('animals').where("animalArray", "array-contains", param1);
let query2 = db.collection('animals').where("animalArray", "array-contains", param2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.