問題描述
我最近詢問如何根據子屬性過濾產品(請參閱:根據 Firebase 中的子子項過濾產品).
I recently asked how to filter products based on their child property (see: Filter products based on the sub child in Firebase).
作為回顧,我的結構如下所示:
As a recap my structure looks as follows:
products/
product1
/author: 12345
/title: "Awesome"
/category: "catA"
/description: "more awesome"
product2
/author: 67890
/title: "Other"
/category: "catB"
/description: "otherawesome"
product3
/author: 12345
/title: "Billy"
/category: "catB"
/description: "otherawesome"
要過濾出作者為 12345
的所有產品,我們可以簡單地使用:
And to filter out all products with author 12345
we can simply use:
ref.child("products").orderByChild('author').equalTo(12345)...
但是,當我有多個 AND 語句或多個 OR 語句時該怎么辦?
如果我想過濾掉怎么辦:
So what if I want to filter out:
作者為
12345
AND 類別catA
的所有產品(返回product1
)
all products with author
12345
AND categorycatA
(returnsproduct1
)
作者為 12345
或作者 67890 的所有產品(返回 product1
和 product3
)
all products with author 12345
OR author 67890 (returns product1
and product3
)
對于第一部分,我嘗試了:
For the first part, I tried:
ref.child("products").orderByChild('author').equalTo(12345).orderByChild('category').equalTo('catA')...
但這不起作用(拋出錯誤You can't combine multiple orderBy calls
)
but that did not work (throws error You can't combine multiple orderBy calls
)
另請參閱:https://www.firebase.com/docs/web/guide/retrieving-data.html#section-queries
推薦答案
根據我的閱讀 這里,這樣做的方法是執行第一個查詢(最好是返回最少結果的那個),然后在javascript中按另一個字段過濾.另一種方法,如果您經常執行此查詢,我建議您這樣做,是為查詢創建一個復合索引,例如;上面鏈接中 Frank van Puffelen 的回答舉了一個例子.
From what I've read here, the way to do this is to perform the first query (preferably the one that will return the fewest results), then filter by the other field in javascript. Another way to do this, and I'd recommend this if you are performing this query often, is create a compound index for the query like; the answer by Frank van Puffelen in the link above gives an example of this.
products/
product1
/author: 12345
/title: "Awesome"
/category: "catA"
/description: "more awesome"
/author_category: "12345_catA"
product2
/author: 67890
/title: "Other"
/category: "catB"
/description: "otherawesome"
/author_category: "67890_catB"
product3
/author: 12345
/title: "Billy"
/category: "catB"
/description: "otherawesome"
/author_category: "12345_catB"
至于或",我已經找了很長時間,但沒有找到對您有幫助的東西.我建議兩個單獨的查詢.
As for the 'OR', I've looked for quite a while and found nothing to help you. I'd suggest two separate queries.
這篇關于在 Firebase 中過濾多個子屬性的產品的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!