【问题标题】:Realm query by two params in list通过列表中的两个参数进行领域查询
【发布时间】:2018-05-18 08:20:17
【问题描述】:

我有两个对象:Author 和 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
}

我在领域中有数据,如下所示:

{ “id”:“作者1”, “书”:[ { “id”:“book1”, “计数页数”:100, “类型”:“幻想” }, { “id”:“book2”, “计数页数”:150, “类型”:“非小说” } ] }

我想查找具有特定类型和特定页数的书籍的作者。如果我这样写:

realmQuery.where().equalsTo("books.countPages", 100).equalsTo("books.genre", "non-fiction").find()

我会找到一位 id = author1 的作者。但这不是真的,我应该得到空列表。

如何编写查询来实现这一点?

【问题讨论】:

    标签: android kotlin realm


    【解决方案1】:

    链接查询转换为has at least one of ___ where X is true,所以

    .equalsTo("books.countPages", 100).equalsTo("books.genre", "non-fiction")
    

    说“作者至少有一本 countPages 100 的书,并且至少有一本非小说类型的书”——这是真的!但这不是你想要的。


    有两种方法可以解决这个问题:

    1.) 查询现有结果集以获得“更小”的结果:

    realmQuery.where()
              .equalTo("books.countPages", 100)
              .findAll()
              .equalTo("books.genre", "non-fiction")
              .findAll()
    

    2.) 对书籍执行查询,通过链接对象反向关系访问作者

    @RealmClass
    class Book {
        @PrimaryKey
        val id: String?
        val countPages: Long
        val genre: String
    
        @LinkingObjects("books")
        val authors: RealmResults<Author>? = null
    }
    

    val books = realm.where<Book>().equalTo("countPages", 100).equalTo("genre", "non-fiction").findAll();
    // these books have `authors` field that contains the author 
    

    【讨论】:

    • 谢谢!两种方式都帮助了我。不知道链接对象。
    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多