gpt4 book ai didi

java - Android:Realm了解LinkingObjects

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:44 24 4
gpt4 key购买 nike

我需要有关 Realm 中 LinkingObjects 的帮助。请看这些简单的代码:

public class Product extends RealmObject
{
@PrimaryKey
private int prodId;

@Required
private String name;

private RealmList<ProductItem> productItems;

@LinkingObjects("productParent")
private final RealmResults<ProductItem> linkProductItems = null;
...
...
...
}

public class ProductItem extends RealmObject
{
@PrimaryKey
private String primaryKey;

private int prodId;

private int prodItemId;

private String itemCode;

private double price;

private Product productParent;
...
...
...
public Product getProductParent()
{
return productParent;
}
}

然后,我通过这样做添加了示例数据:

realm.beginTransaction();

Product prod = new Product();
prod.setProdId(1);
prod.setName("Test");
prod = realm.copyToRealm(prod);

ProductItem prodItem = new ProductItem();
prodItem.setProdId(prod.getProdId());
prodItem.setProdItemId(1);
prodItem.setItemCode("00231");
prodItem.setPrice(9.95);
prodItem.getProductItems().add(realm.copyToRealm(prodItem));

realm.commitTransaction();

现在,根据我的理解,LinkingObjects 允许您引用您的 parent ?但是下面的代码会失败:

String sOutput = "";
for (ProductItem prodItem : realm.where(ProductItem.class).findAll())
sOutput += prodItem.getProductParent().getName() + "\n";

问题是 bqItem.getProductParent() 为 NULL。我的问题是,我是否正确完成了 LinkingObjects?如果没有,你能帮帮我吗?

谢谢

最佳答案

你在找

public class Product extends RealmObject
{
@PrimaryKey
private int prodId;

@Required
private String name;

private RealmList<ProductItem> productItems;

//@LinkingObjects("productParent")
//private final RealmResults<ProductItem> linkProductItems = null;
...
...
...
}

public class ProductItem extends RealmObject
{
@PrimaryKey
private String primaryKey;

private int prodId;

private int prodItemId;

private String itemCode;

private double price;

//private Product productParent;

@LinkingObjects("productItems") // <-- !
private final RealmResults<Product> productParents = null; // <-- !
...
...
...
public RealmResults<Product> getProductParents() // <-- !
{
return productParents;
}
}

关于java - Android:Realm了解LinkingObjects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43759247/

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