Subquery and IN Statement in realm

前端 未结 1 516
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 13:44

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

相关标签:
1条回答
  • 2020-12-22 14:28

    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);
    }
    
    0 讨论(0)
提交回复
热议问题