在一个查询中查询两个表 - 解析
问题描述:
是否有可能从两个查询返回对象?例如:在一个查询中查询两个表 - 解析
PFQuery *queryOne = [PFQuery queryWithClassName:@"User"];
[query whereKey:@"status" equalTo:@"Happy"];
PFQuery *queryTwo = [PFQuery queryWithClassName:@"Places"];
[query whereKey:@"type" equalTo:@"restaurant"];
PFQuery *join = // somehow join both queryOne and queryTwo
[join findObjectsInBackgroundWithBlock:^(NSArray *result, NSError *error) {
// here result would contain objects from both queryOne and queryTwo
}];
所以如果queryOne将返回用户A,B,C和queryTwo将返回的地方d,E,F则导致将包含[A,B,C,d,E,F]
这可能吗?如果不是,获得两个异步请求结果的最佳方式是什么?我基本上想要在tableview中显示这些数据,但不想显示任何东西,直到我有两个查询的合并结果...
答
对不起,我不能给你任何Objective-C代码,因为我只在Swift中完成了这个工作,但我做了两个嵌套查询以及调度组。就我而言,这两个不同的课程是相关的,但无论如何你都可以做到。
在斯威夫特,可能那种看起来像这样:
//Create Dispatch Group
let group = dispatch_group_create()
let query1 = PFQuery(className: "User")
query.whereKey("status", isEqualTo: "Happy")
dispatch_group_join(group)
query.findObjectsInBackgroundWithBlock {
//Your block, might add model objects to array or similar
(objects: [AnyObject]?, error: NSError?) -> Void in
for object in objects {
myArray.append(object)
}
dispatch_group_leave(group)
}
let query2 = PFQuery(className: "Places")
query.whereKey("type", isEqualTo: "restaurant")
dispatch_group_join(group)
query.findObjectsInBackgroundWithBlock{
//Same thing as above, maybe another array or something, and in the end
dispatch_group_leave(group)
}
//This is a "listener" for when the groups are finished
dispatch_group_notify(group, dispatch_get_main_queue())
{
println("All done")
//reload TableView when all data is Fetched
self.tableView.reloadData()
}
我这个成功用于获取数据的阵列。对于Swift感到抱歉,如果你喜欢这种方法,我可以尝试帮助你将其中的一部分翻译成Obj-C。 Grand Central Dispatch Groups是您的Google术语。
你想从两个表中查询的对象之间是否存在关系?据我所知,在单个查询中没有方法从两个不同的类中获取数据。 – kRiZ