【问题标题】:How do I check if 3 or more values are the same in my Firebase database?如何检查我的 Firebase 数据库中的 3 个或更多值是否相同?
【发布时间】:2017-04-21 04:04:15
【问题描述】:

我目前正在尝试返回我的表格视图中具有 3 个属性等于“艺术”、“音乐”和“体育”的所有用户。具有不等于这 3 个字符串的 3 个属性的其他用户将不会显示在我的表格视图中。我如何实现这一目标?目前,我只能检查 ONE 属性是否等于 ONE 字符串,如下面的示例所示。下面是我的数据库树的图像,以及我目前拥有的代码。任何感谢任何帮助。谢谢!

class User: NSObject {

    var name: String?
    var email: String?
    var numberId: String?

    var attribute1: String?
    var attribute2: String?
    var attribute3: String?

    var password: String?
    var profileImageUrl: String?
}

func fetchUser() {

        FIRDatabase.database().reference().child("users").queryOrdered(byChild: "attribute1").queryEqual(toValue: "art").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User()

                user.setValuesForKeys(dictionary)

                self.users.append(user)

                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }

        }, withCancel: nil)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell

        let user = users[indexPath.row]
        cell.textLabel?.text = user.name
        cell .detailTextLabel?.text = user.email

        if let profileImageUrl = user.profileImageUrl {

            cell.profileImageView.loadImageUsingCachWithUrlString(urlString: profileImageUrl)
        }

        return cell
    }

【问题讨论】:

    标签: swift xcode firebase swift3 firebase-realtime-database


    【解决方案1】:

    Firebase 的一个(在我看来是主要的)限制是它无法同时通过多个键进行过滤。执行此操作的一般策略是按您认为可以为您提供最小数据集的键进行过滤,并按客户端的剩余键进行过滤。因此,例如,如果您认为您当前的过滤器将为您提供最小的集合(或者如果它们都提供大致相同的),那么在添加用户之前,请检查:

    if user.attribute2 == "music" && user.attribute3 == "sports" {
        self.users.append(user)
    }
    

    您还可以在拥有所有用户后过滤您的列表。但关键是 Firebase 目前不允许这种过滤,所以你需要在客户端进行。

    self.users = self.users.filter({ $0.attribute2 == "music" && $0.attribute3 == "sports" })
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多