我有三个不同的模型部门,子部门和员工
@interface Department : RLMObject
@property NSString *name;
@property (nonatomic, strong) RLMArray<SubDepartment> *subDepartments;
@property (nonatomic, strong) RLMArray<Employee> *employees;
@end
@interface SubDepartment : RLMObject
@property NSString *name;
@property (nonatomic, strong) RLMArray<Employee> *employees;
@end
@interface Employee : RLMObject
@property NSString *department;
@property NSString *email;
@property NSString *firstname;
@property NSString *lastname;
@property NSString *fullname;
@property NSString *imgUrl;
@property NSString *imgWall;
@property NSString *nickname;
@end
我想搜索哪个部门的员工包含&#34; a&#34;以他们的名字和姓氏,并且还希望搜索名称包含&#34; a&#34;的子部门员工。用他们的名字和姓氏。
我试图这样做。
RLMResults *subdepartments = [SubDepartment objectsWhere:
[NSString stringWithFormat:@"SUBQUERY(employees, $e, $e.firstname contains '%@' OR $e.lastname contains '%@' OR $e.fullname contains '%@' OR $e.nickname contains '%@').@count > 0",searchText,searchText,searchText,searchText]];
NSMutableArray *subDepartmentNames = [NSMutableArray array];
for (SubDepartment *subDepartment in sections)
{
[subDepartmentNames addObject:subDepartment.name];
}
RLMResults *departments = [Department objectsWhere:
[NSString stringWithFormat:@"SUBQUERY(employees, $e, $e.firstname contains '%@' OR $e.lastname contains '%@' OR $e.fullname contains '%@' OR $e.nickname contains '%@').@count > 0",searchText,searchText,searchText,searchText]];
RLMResults<Department *> *filteredDepartments = [departments objectsWhere:
[NSString stringWithFormat:@"SUBQUERY(subDepartments, $d, $d.name IN '%@').@count > 0",sectionNames]];
答案 0 :(得分:1)
也许您不需要使用子查询。更简单地说,您可以在查询中使用ANY
,如下所示:
[Department objectsWhere:
@"ANY employees.firstname CONTAINS %@ OR ANY employees.lastname CONTAINS %@ OR ANY subDepartments.employees.firstname CONTAINS %@ OR ANY subDepartments.employees.lastname CONTAINS %@", searchText, searchText, searchText, searchText];
但我认为使用反向关系更容易。在Realm中,反向关系定义为RLMLinkingObjects
。
您可以按如下方式向User
类添加反向关系:
@interface Employee : RLMObject
...
@property (readonly) RLMLinkingObjects *departments;
@property (readonly) RLMLinkingObjects *subDepartments;
@end
@implementation User
+ (NSDictionary *)linkingObjectsProperties {
return @{@"departments": [RLMPropertyDescriptor descriptorWithClass:Department.class propertyName:@"employees"],
@"subDepartments": [RLMPropertyDescriptor descriptorWithClass:SubDepartment.class propertyName:@"employees"]};
}
@end
然后,您可以从User
的属性获取用户所属的部门和部分,如下所示:
RLMResults *employees = [Employee objectsWhere:@"firstname CONTAINS %@ OR lastname CONTAINS %@" , searchText, searchText];
for (Employee *employee in employees) {
NSLog(@"%@", employee.departments);
NSLog(@"%@", employee.subDepartments);
}