gpt4 book ai didi

swift - 过去 7 天最喜欢的商品?

转载 作者:行者123 更新时间:2023-11-30 10:42:42 28 4
gpt4 key购买 nike

我正在为我的应用使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com