本文介绍了通过列表中的两个参数进行领域查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象:作者和书.

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

我将得到一位ID = author1的作者.但这不是真的,我应该得到一个空名单.

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?

推荐答案

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

Link queries translate to has at least one of ___ where X is true, so

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

说作者至少有一本具有countPages 100的书,并且至少有一本具有非小说类型的书" –是的!但这不是您想要的.

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.)查询现有结果集以获取较小"结果:

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.)在Books上执行查询,并通过链接对象逆向关系访问Author

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
}

还有

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

这篇关于通过列表中的两个参数进行领域查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:45