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?
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]]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With