Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying on relationship arrays in Realm

Lets say I have a Dog and Person realm objects like

@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 the sample code from Realm's example project. The only difference is that Dog entity has an array of Person objects as owners, in other words an inverse relationship to Person's dogs.

Now the thing I want to accomplish is querying the Dog objects having a Person as one of the owners.

How can I do that?

like image 256
iltercengiz Avatar asked Aug 11 '14 11:08

iltercengiz


Video Answer


1 Answers

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

A complete 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]]);
}
like image 198
Thomas Goyne Avatar answered Nov 03 '22 00:11

Thomas Goyne