首页 > 解决方案 > 搜索 Firebase 数据库

问题描述

需要在 5/products/ 中找到所有标题:“Orange's” 这是我的结构:

"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

标签: swiftfirebasesearchfirebase-realtime-database

解决方案


使用下面的代码在 ids 中获取 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)

推荐阅读