Hi. I have a RealmObject
subclass called Article
which has an id
field (it's and int
and also a @PrimaryKey
). I would like to pass to a query a list of int
s (a Set<>
, int[]
, or whatever) of article id's and retrieve only those articles.
In SQL would be like this:
SELECT *
FROM `table`
where ID in (5263, 5625, 5628, 5621)
I've seen it's possible to do this in iOS in this StackOverflow question.
How can I do this in Android? Thanks!
Unfortunately, Realm java currently has no support for this so you have to build up an OR query manually to achieve the same thing.
RealmQuery<MyRealmObject> query = realm.where(MyRealmObject.class);
int i = 0;
for (int id : ids) {
if (i++ > 0)
query = query.or();
query = query.equalsTo("id", id);
}
query.beginGroup(); and query.endGroup(); can be used around the for loop if you need to select on some other parameters too.
@albertvilacalvo As @knighty said, Realm Java does not support IN
query.
The code for building the query can be a bit shorter.
RealmQuery<MyRealmObject> query = realm.where(MyRealmObject.class);
for (int id : ids) {
query = query.or().equalsTo("id", id);
}
IN operator issue is tracked as #841 and also #1280 is helpful.
I'll close this issue as a duplicate of #841. If you have further questions, feel free to reopen this or create new issue.
Thank you all. Because I want to return an empty RealmResults<Article>
if the list of ids is empty, that's what I ended up doing:
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 basket 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 ("Missing right-hand side of OR")
if (i++ > 0) {
query = query.or();
}
query = query.equalTo("id", id);
}
}
Most helpful comment
Thank you all. Because I want to return an empty
RealmResults<Article>
if the list of ids is empty, that's what I ended up doing: