在一个查询中查询两个表 - Parse

时间:2015-07-20 03:49:19

标签: sql objective-c parse-platform

是否可以从两个查询中返回对象?例如:

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中显示这些数据,但是在我从两个查询中得到合并结果之前不想显示任何内容......

1 个答案:

答案 0 :(得分:0)

对不起,我不能给你任何Objective-C代码,因为我只在Swift中完成了这个,但我做了两个嵌套查询,以及调度组。就我而言,两个不同的类是相关的,但无论如何你都可以这样做。

在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术语。