最近7天内最受欢迎的商品?

时间:2019-06-04 21:13:48

标签: swift google-cloud-firestore

我正在为我的应用程序使用Firestore,并希望能够在过去7天内发布最受欢迎的商品。在理想的情况下,呼叫将类似于:

        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day], from: Date())
        let start = calendar.date(from: components)!
        let startDate = calendar.date(byAdding: .day, value: -7, to: start)!
        let startDateStamp: Timestamp = Timestamp(date: startDate)

        let mostLiked = colRef
        .whereField("isReported", isEqualTo: false)
        .whereField("timestamp", isGreaterThanOrEqualTo: startDateStamp)
        .order(by: "likeCount", descending: true)
        .limit(to: 1)

        mostLiked.getDocuments { (snapshot, error) in
            if let error = error { return }
            guard let snap = snapshot else { return }

            for document in snap.documents {
                let data = document.data()
                print(data)
            }
        }

但这显然是不允许的。

我最终得到了:

        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day], from: Date())
        let start = calendar.date(from: components)!
        let startDate = calendar.date(byAdding: .day, value: -7, to: start)!
        let startDateStamp: Timestamp = Timestamp(date: startDate)

        let mostLiked = colRef
        .whereField("isReported", isEqualTo: false)
        .whereField("timestamp", isGreaterThanOrEqualTo: startDateStamp)
        .order(by: "timestamp", descending: true)

        mostLiked.getDocuments { (snapshot, error) in
            if let error = error { return }
            guard let snap = snapshot else { return }

            for document in snap.documents {
                let data = document.data()
                ...
                 data handling code to fill struct - newTopItem
                ...

                if self.topLikedArray.isEmpty {
                    self.topLikedArray.append(newTopItem)
                } else {
                    if likeCount > self.topLikedArray[0].likeCount! {
                        self.topLikedArray.removeAll()
                        self.topLikedArray.append(newTopItem)
                    }
                }
            }
           print("Top Item: \(self.topLikedArray)")
        }

过去7天内获取了所有内容,我将不得不手动进行排序以获取最大的likeCount,这对我来说似乎有点笨拙,更不用说它提出的可伸缩性问题了,因为我不能将结果限制为只是1.有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

    let mostLiked = bleatsRef
        .whereField("isReported", isEqualTo: false)
        .whereField("timestamp", isGreaterThanOrEqualTo: startDateStamp)
        .order(by: "likeCount", descending: true)
        .limit(1)

    mostLiked.getDocuments { (snapshot, error) in
        guard
            error == nil, 
            let snap = snapshot 
            else { return }

        print("The most liked document is: \(snap.documents.first)")
    }