我正在为我的应用程序使用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。有一个更好的方法吗?

最佳答案

    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)")
    }

关于swift - 最近7天内最受欢迎的商品?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56451441/

10-09 22:01