【发布时间】:2023-03-09 20:30:02
【问题描述】:
我需要有关 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?如果没有,你能帮帮我吗?
谢谢
【问题讨论】:
-
你能在 tblProductItem 类中试试
private tblProduct tblProductParent = new tblProduct(); -
什么是
BanquetItem?以上代码为ProductItem? -
@EpicPandaForce, upsss... 抱歉... LOL... 从错误的项目中复制并粘贴错误的代码。我已经更正了代码。它应该是 ProductItem。