我需要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允许您回复您的父母?但是以下代码将失败:
String sOutput = "";
for (ProductItem prodItem : realm.where(ProductItem.class).findAll())
sOutput += prodItem.getProductParent().getName() + "\n";
问题是 bqItem.getProductParent() 为NULL。我的问题是,我是否正确完成了LinkingObjects?如果没有,你能帮助我吗?
由于
答案 0 :(得分:5)
您正在寻找
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;
}
}