访问多对多关系的对象

时间:2014-06-06 17:15:17

标签: objective-c parse-platform

我有一个具有多对多关系的对象。它进入锻炼< - >>锻炼得分。如果我有锻炼分数,我该如何进入锻炼?我正在使用Parse.com。

假设workoutScore是一个PFObject,并且已被检索,我有一个名为whichWorkout的关系。返回的对象是锻炼,但我无法访问它的属性。我做错了吗?

// Assuming this score has been retrieved by a PFQuery
PFObject *workoutScore;
PFObject *actualWorkout = workoutScore[@"whichWorkout"];
// Now when I try to access a property of actualWorkout, I can't
NSString *name = actualWorkout[@"name"];

如果我只是查询实际锻炼,相同的代码可以正常工作。有没有办法使用Parse?

访问通过指针关系检索的对象的属性

3 个答案:

答案 0 :(得分:1)

如果WorkoutScore有一个指向Workout的后退指针(它看起来像你的代码那样,名为whichWorkout),那么它很容易。查询WorkoutScore时,使用includeKey:积极获取相关对象:

[workoutScoreQuery includeKey:@"whichWorkout"];

答案 1 :(得分:1)

如果您在workoutScore上运行查询,则应使用[query include:@"workout"]。这将拉出被指向的对象(actualWorkout),并在一次调用中获得所需的一切

PFQuery query = [PFQuery queryWithClassName:@"WorkoutScore"];
[query includeKey:@"workout"];
[query findAllInBackground....

另一种选择是在实际锻炼时调用fetch。这是获取workoutScore后的第二个电话。如果你知道你将需要锻炼,可能最好在查询过程中使用include。

PFObject *actualWorkout = workoutScore[@"whichWorkout"];

// There are asynchronous versions of fetch too
// which would be recommended
[actualWorkout fetch]; 

// actualWorkout will now have its data.
NSString *name = actualWorkout[@"name"];

答案 2 :(得分:1)

如果多对多关系是PFRelation,那么您必须将其作为第二步查询

PFRelation *relation = [parseObject relationForKey:@"relationName"];
PFQuery *query = [[relation query] findObjectsInBackground:...];

如果多对多关系只是一个指针数组,则需要告诉查询包含实际数据:

[workoutScoreQuery includeKey:@"whichWorkout"];