这是我正在使用的对象:
public class NavigationMenuModule extends RealmObject implements Parcelable {
@PrimaryKey
public String sectionKey;
public RealmList<ItemModule> modules;
public RealmList<Article> spotlightSponsored;
public RealmList<Article> items;
}
儿童文章对象:
public class Article extends RealmObject {
@PrimaryKey
public String contentId;
public String leadImageURL;
public String summary;
public String headline;
}
我将如何构建此领域调用:
下面的方法有效但我觉得可能有一种“整洁”的方式:
public static Article getArticle(String sectionKey, String articleId) {
Realm realm = Realm.getDefaultInstance();
NavigationMenuModule navigationMenuModule = realm.where(NavigationMenuModule.class).equalTo("sectionKey", sectionKey).findFirst();
if (navigationMenuModule != null && !navigationMenuModule.spotlightSponsored.isEmpty()) {
for (Article article : navigationMenuModule.spotlightSponsored) {
if (article.getContentId().equals(articleId)) {
Article ret = realm.copyFromRealm(article);
realm.close();
return ret;
}
}
}
realm.close();
return null;
}
答案 0 :(得分:1)
理论上这应该适用于Realm 3.5.0
public class NavigationMenuModule extends RealmObject implements Parcelable {
@PrimaryKey
public String sectionKey;
public RealmList<ItemModule> modules;
public RealmList<Article> spotlightSponsored;
public RealmList<Article> items;
}
public class Article extends RealmObject {
@PrimaryKey
public String contentId;
public String leadImageURL;
public String summary;
public String headline;
@LinkingObjects("spotlightSponsored")
public final RealmResults<NavigationMenuModule> spotlightSponsoredOf = null;
@LinkingObjects("items")
public final RealmResults<NavigationMenuModule> itemsOf = null;
}
public static Article getArticle(Realm realm, String sectionKey, String articleId) {
return realm.where(Article.class)
.equalTo("contentId", articleId)
.equalTo("spotlightSponsoredOf.sectionKey", sectionKey)
.findFirst();
}