这是我正在使用的对象:

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;
    }


我将如何构造此领域调用:


通过sectionKey获取NavigationMenuModule项
在与文章的contentId匹配的NavigationMenuModule中获得SpotlightSponsored


下面的方法有效,但是我觉得可能有一种“更整洁”的方式:

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;
}

最佳答案

从理论上讲,这应该与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();
}

10-08 16:42