Realm query by two params in list

情到浓时终转凉″ 提交于 2019-12-14 03:57:24

问题


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?


回答1:


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 


来源:https://stackoverflow.com/questions/50406850/realm-query-by-two-params-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!