搜索Firebase数据库

时间:2019-01-02 20:44:57

标签: swift firebase search firebase-realtime-database

需要在5 /产品/中找到所有标题:“橙色” 这是我的结构:

"5"
   "products"
             "1" (ShopID)
                "Drink" (Category)
                       "id111" (ID)
                              title: "Milk"
                       "id121"
                              title: "Water"
                       "id133"
                              title: "Orange juice"
                "Fruit"
                       "id2211"
                              title: "Apple"
                       "id3121"
                              title: "Mango"
                       "id5134"
                              title: "Orange"
                "Fish"
                       "id2411"
                              title: "Fish"
                       "id3221"
                              title: "Shark"
                       "id5734"
                              title: "Orange Fish"
             "2"
                 "Home"
                       "id22411"
                              title: "Orange table"
                       "id33221"
                              title: "Spoon"
                       "id45734"
                              title: "Orange socks"
             "3"
                ....

这是我的代码:

let messagesRef = Database.database().reference().child("5/products/").queryOrdered(byChild: "title").queryStarting(atValue: "Orange").queryEnding(atValue: "Orange"+"\u{f8ff}")
messagesRef.observeSingleEvent(of: .value)

是否可以在单个查询中找到结果?如果我不知道ID,类别

这种方法很好用

Database.database().reference().child("5/products/1/Drink/").queryOrdered(byChild: "title").queryStarting(atValue: "Orange").queryEnding(atValue: "Orange"+"\u{f8ff}")

但是我需要找到Category和ShopID

1 个答案:

答案 0 :(得分:0)

利用以下代码获取id中Orange的引用

 let ref = Database.database().reference().child("5/products")
    ref.observe(.childAdded, with: { (snapshot) in
        //print(snapshot)
        guard let dictionary = snapshot.value as? [String : AnyObject] else {
            return
        }
       //print(dictionary)
        for (key, value) in dictionary{
            //print(value)
            if let innerDict = value as? NSDictionary{
                for (k, v) in innerDict{
                    if let str:String = v as? String{
                        if str.lowercased().contains("orange"){
                            print("id : \(k)  and Category : \(key)")
                        }
                    }
                }
            }

        }
    }, withCancel: nil)