I have two objects: Author and Book.
@RealmClass
class Author {
@PrimaryKey
val id: String?
val books: RealmList<Book> = RealmList()
}
@RealmClass
class Book {
@PrimaryKey
val id: String?
val countPages: Long
val genre: String
}
And I have data in realm, like this:
{
"id": "author1",
"books": [
{
"id": "book1",
"countPages": 100,
"genre": "fantasy"
},
{
"id": "book2",
"countPages": 150,
"genre": "non-fiction"
}
]
}
I want to find authors with books, which have specific genre and specific pages count. If I write something like this:
realmQuery.where().equalsTo("books.countPages", 100).equalsTo("books.genre", "non-fiction").find()
I'll get one author with id = author1. But it's not true, I should get empty list.
How can I write query to achieve this?
Link queries translate to has at least one of ___ where X is true
, so
.equalsTo("books.countPages", 100).equalsTo("books.genre", "non-fiction")
Says "author that has at least one book that has countPages 100, and has at least one book that has genre non-fiction" -- which is true! But it is not what you want.
There are two ways to go about this:
1.) query the existing result set to get a "smaller" result:
realmQuery.where()
.equalTo("books.countPages", 100)
.findAll()
.equalTo("books.genre", "non-fiction")
.findAll()
2.) execute the query on Books, and access the Author via linking objects inverse relationship
@RealmClass
class Book {
@PrimaryKey
val id: String?
val countPages: Long
val genre: String
@LinkingObjects("books")
val authors: RealmResults<Author>? = null
}
And
val books = realm.where<Book>().equalTo("countPages", 100).equalTo("genre", "non-fiction").findAll();
// these books have `authors` field that contains the author