I have three realm objects. Department, section and user. section is a kind of sub department in a department. But there will be users under each section and each department
Maybe you do not need to use subquery. More simply, you can use ANY
in query like the following:
[Department objectsWhere:
@"ANY users.firstname CONTAINS %@ OR ANY users.lastname CONTAINS %@ OR ANY sections.users.firstname CONTAINS %@ OR ANY sections.users.lastname CONTAINS %@", searchText, searchText, searchText, searchText];
But I think using inverse relationships is more easier. In Realm, inverse relationships is defined with RLMLinkingObjects
.
You can add inverse relationships to User
class as follows:
@interface User : RLMObject
...
@property (readonly) RLMLinkingObjects *departments;
@property (readonly) RLMLinkingObjects *sections;
@end
@implementation User
+ (NSDictionary *)linkingObjectsProperties {
return @{@"departments": [RLMPropertyDescriptor descriptorWithClass:Department.class propertyName:@"users"],
@"sections": [RLMPropertyDescriptor descriptorWithClass:Section.class propertyName:@"users"]};
}
@end
Then you can get departments and sections where the user belongs to from User
's property, like the following:
RLMResults *users = [User objectsWhere:@"firstname CONTAINS %@ OR lastname CONTAINS %@" , searchText, searchText];
for (User *user in users) {
NSLog(@"%@", user.departments);
NSLog(@"%@", user.sections);
}