Android上的领域 - 如何通过ID列表选择多个对象(@PrimaryKey)?

时间:2015-11-11 13:29:11

标签: android realm

我正在使用Realm数据库构建Android应用程序。

我有一个名为RealmObject的{​​{1}}子类,其中包含Article字段(' s和id以及int)。我想向查询传递一个@PrimaryKey s(intSet或其他)文章ID的列表,并仅检索这些文章。

在SQL中会是这样的:

int[]

我已经看到可以在this StackOverflow question的iOS中执行此操作。

我怎样才能在Android中执行此操作?谢谢!

修改:为了通知,我也在GitHub回购here上询问了这个问题。

5 个答案:

答案 0 :(得分:24)

更新:

Realm 1.2.0添加了RealmQuery.in()以便与多个值进行比较。 The documentation详细说明了所有可用的重载。如果我们的ID是Integer s:

,我们可以使用This one
public RealmQuery<E> in(String fieldName, Integer[] values)

原始回答:

如果id列表为空,@ ChristianMelchior的答案将返回所有文章。我希望它返回一个空的RealmResults<Article>。这就是我最终做的事情;

Set<Integer> articleIds = this.getArticleIds();
RealmQuery<Article> query = realm.where(Article.class);
if (articleIds.size() == 0) {
    // We want to return an empty list if the list of ids is empty. 
    // Just search for an id that does not exist.
    query = query.equalTo("id", -30000);
} else {
    int i = 0;
    for (int id : articleIds) {
        // The or() operator requires left hand and right hand elements. 
        // If articleIds had only one element then it would crash with
        // "Missing right-hand side of OR"
        if (i++ > 0) {
            query = query.or();
        }
        query = query.equalTo("id", id);
    }
}
return query.findAll();

答案 1 :(得分:4)

现在,领域v 1.2.0支持RealmQuery.in()以便与多个值进行比较。

答案 2 :(得分:3)

The Realm Java API's doesn't support this yet unfortunately. You can follow the feature request here https://github.com/realm/realm-java/issues/841

The current work-around would be to build up the query yourself in a for-loop:

RealmResults<Article> articles = realm.allObjects(Article.class);
RealmQuery q = articles.where();
for (int id : ids) {
    q = q.equalTo("id", id);
}
RealmResults<Article> filteredArticles = q.findAll();

答案 3 :(得分:2)

这是Realm从1.2.0开始的方式:

public RealmQuery<E> in(String fieldName, String[] values) {
    if (values == null || values.length == 0) {
        throw new IllegalArgumentException(EMPTY_VALUES);
    }
    beginGroup().equalTo(fieldName, values[0]);
    for (int i = 1; i < values.length; i++) {
        or().equalTo(fieldName, values[i]);
    }
    return endGroup();
}

以前this就是这样做的

答案 4 :(得分:1)

我刚刚看到这篇文章,我想我可以在这上面投入2美分。尽管我很欣赏Christian Melchior和他的答案,但我认为在这种情况下他的答案是行不通的(至少在当前版本中)。

我更喜欢这样做 - 我个人认为它比Albert Vila的答案更具可读性:

runfile('E:/python_practice/task2/gen1.py', wdir='E:/python_practice/task2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)
  File "C:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
  File "E:/python_practice/task2/gen1.py", line 10, in <module>
    from xlutils.copy import copy
ImportError: No module named 'xlutils'
相关问题