Firebase Firestore多次查询

时间:2017-12-05 06:38:26

标签: ios swift xcode firebase google-cloud-firestore

嗨,我正在尝试在查询之上添加过滤器,但是,它无效。它导致代码无用的重复。有人能帮助我吗?

有没有办法将更多的.whereField添加到一个现有的Ref?

谢谢! 威廉

        var usersRef:Query

    if (DAgeMin == DAgeMax) {
        if (DGender == "Both") {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isEqualTo: DAgeMin as Any)
            // usersRef.limit(to: 1)
        }
    } else {
        if (DGender == "Both") {

            usersRef = Firestore.firestore().collection("users")
            // Not working, filters aren't being applied
                usersRef
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)


            // usersRef.limit(to: 1)
        } else {
            usersRef = Firestore.firestore().collection("users")
                .whereField("AccountCompleted", isEqualTo: true)
                .whereField("Banned", isEqualTo: 0)
                .whereField("Gender", isEqualTo: DGender as Any)
                .whereField("Age", isGreaterThanOrEqualTo: DAgeMin as Any)
                .whereField("Age", isLessThanOrEqualTo: DAgeMax as Any)
            // usersRef.limit(to: 1)

        }
    }
    // How can I apply this filter to all the usersRef, without putting it after each "block"
    usersRef.limit(to: 1)


    usersRef.getDocuments() { (querySnapshot, err) in

2 个答案:

答案 0 :(得分:2)

我在javascript中遇到了类似的问题。我对swift并不熟悉所以语法会有所不同,但希望它也可以帮助你。

const userRef = firebase.firestore().collection("users");
var query = userRef.where("AccountCompleted", "==", true);


if (condition) {
    query = query.where("color", "==", "red");
}
else {
    query = query.where("color", "==", "blue");
}


if (differentCondition) {
    query = query.where("number", "==", 10);
}
else {
    query = query.where("number", "==", 12);
}


query = query.limit(1);

这允许我根据条件链接不同的where()方法,然后在完成构建查询后添加limit()方法。

答案 1 :(得分:0)

你必须在'ifs'之外设置常见的'whereField',在'ifs'中你必须设置特定的'whereField'