gpt4 book ai didi

android - 带有子数组的 Realm 查询

转载 作者:行者123 更新时间:2023-11-30 00:24:01 24 4
gpt4 key购买 nike

这是我正在使用的对象:

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

我将如何构建这个 Realm 调用:

  1. 通过sectionKey获取NavigationMenuModule
  2. 在与文章的 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();
}

关于android - 带有子数组的 Realm 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com