Query in relationship arrays in Realm

Suppose I have objects in the scope of Dog and Person , such as

 @interface Dog : RLMObject @property NSString *name; @property NSInteger age; @property RLMArray<Person> *owners; @end @implementation Dog @end RLM_ARRAY_TYPE(Dog) @interface Person : RLMObject @property NSString *name; @property RLMArray<Dog> *dogs; @end @implementation Person @end RLM_ARRAY_TYPE(Person) 

This is sample code from the Realm sample project. The only difference is that the Dog object has an array of Person objects as owners , in other words, the inverse of Person dogs .

Now what I want to accomplish is querying Dog objects that have Person as one of the owners .

How can i do this?

+6
source share
1 answer

You just need to do [Dog objectsWhere:@"ANY owners = %@", person] , where person is the owner you want to request.

Full example:

 @protocol Person; @interface Dog : RLMObject @property NSString *name; @property NSInteger age; @property RLMArray<Person> *owners; @end @implementation Dog @end RLM_ARRAY_TYPE(Dog) @interface Person : RLMObject @property NSString *name; @property RLMArray<Dog> *dogs; @end @implementation Person @end RLM_ARRAY_TYPE(Person) void test() { RLMRealm *realm = RLMRealm.defaultRealm; [realm beginWriteTransaction]; Person *person = [Person createInRealm:realm withObject:@{@"name": @"Tim"}]; Dog *dog = [Dog createInRealm:realm withObject:@{@"name": @"Rover", @"age": @5, @"owners": @[person]}]; [Dog createInRealm:realm withObject:@{@"name": @"Rex", @"age": @10, @"owners": @[]}]; [realm commitWriteTransaction]; RLMArray *dogs = [Dog objectsWhere:@"ANY owners = %@", person]; assert(dogs.count == 1); assert([dog isEqual:dogs[0]]); } 
+11
source

Source: https://habr.com/ru/post/973646/


All Articles