6

可以说我有一个DogPerson领域对象,例如

@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)

这是来自 Realm 示例项目的示例代码。唯一的区别是Dogentity 有一个Person对象数组 as owners,换句话说就是与Person's的反比关系dogs

现在我想要完成的事情是查询Dog具有 aPerson作为owners.

我怎样才能做到这一点?

4

1 回答 1

11

您只需要做[Dog objectsWhere:@"ANY owners = %@", person]person您要查询的所有者在哪里。

一个完整的例子:

@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]]);
}
于 2014-08-11T21:49:44.823 回答