如何正确实现 Parse 查询以获取有序数据
Posted
技术标签:
【中文标题】如何正确实现 Parse 查询以获取有序数据【英文标题】:How to implement Parse query properly to get ordered data 【发布时间】:2018-04-07 16:45:24 【问题描述】:我有以下代码从两个查询中构建一个查询。
问题是结果没有按updateAt排序。
可能是什么问题?
let ownerQuery = PFQuery(className: "requests")
ownerQuery.whereKey("owner", equalTo: forUser)
ownerQuery.whereKey("stage", equalTo: "initiated")
let requestQuery = PFQuery(className: "requests")
requestQuery.whereKey("requested_by", equalTo: requestedBy)
requestQuery.whereKey("stage", equalTo: "accepted")
// fetch all request of current user as requestor or lender/seller
let query = PFQuery.orQuery(withSubqueries: [ownerQuery, requestQuery])
query.includeKey("requested_by")
query.includeKey("owner")
query.order(byDescending: "updatedAt")
【问题讨论】:
只是猜测...也许您需要通过includeKey
在结果集中包含排序键(updatedAt
)才能使排序工作...?
【参考方案1】:
问题原来是我正在处理检索到的数据的代码。解析返回的排序结果。
我有以下代码影响订购。似乎是因为 getDetails() 异步返回。
所以我在返回之前添加了数组排序。我一次检索 20 行,所以我猜对每个数组进行排序应该不会很昂贵。
我也在GitHub 上发过帖子。等待确认。
query.findObjectsInBackground (results, error) in
if error == nil
for result in results!
group.enter()
let stage = result["stage"] as! String
let requestedBy = result["requested_by"] as! PFUser
DBHelper.getDetails(result["requested_id"] as! String, callbackFunction: (requestedItem) in
let owner = result["owner"] as! PFUser
let request = Request()
request.requestId = result.objectId
request.item = requestedItem
request.owner = owner
request.lastUpdatedDate = result.updatedAt
requestsFound.append(request)
group.leave()
)
group.notify(queue: DispatchQueue.global(qos: .background), execute:
DispatchQueue.main.async
requestsFound.sort (request1:Request, request2:Request) -> Bool in
request1.lastUpdatedDate! < request2.lastUpdatedDate!
callbackFunction(requestsFound,nil)
)
else
// encountered error from Parse
DispatchQueue.main.async
callbackFunction(requestsFound,error! as NSError) // to represent error at backend server
//end of findObjectsInBackground
【讨论】:
【参考方案2】:试试这个:
ownerQuery.order(byAscending: "updatedAt")
【讨论】:
在 PFParameterAssert(subquery.state.sortKeys.count == 0, @"OR 查询不支持带顺序的子查询");我找到了解决方法。单独发布。以上是关于如何正确实现 Parse 查询以获取有序数据的主要内容,如果未能解决你的问题,请参考以下文章