如何只保存 RealmObject 但不保存引用对象

How to save only RealmObject but not referenced object

在我的应用程序中,我有以下 RealmObjects:

产品 - 这作为主数据,不应修改。
购物车 - 购物车让人们挑选要买的东西。内容将为选择类型。
选择 - 表示用户 select 与颜色、尺寸等额外偏好一起编辑的产品

用例
用户 select 产品并添加到购物车。产品被包裹在 Selection 中并存储在 Cart 中。说选择产品 A、B 和 C。

现在将其保存到 Realm 中。文档告诉我使用 RealmList 添加关系。这使得购物车->列表;选择 -> 产品。

然后,如果我使用 copyToRealm,我将在 Product 上得到 PrimaryKey 异常。 由于我只想保存 购物车和选择 ,我如何将选择 link 保存到产品(用于读取备份)而不保存它。

如果我使用 copyToRealmOrUpdate,我是否有意外更新产品的风险?

您可以从一开始就在 Realm 中显式创建 RealmObject,然后将对象 link 设置为托管对象中的托管对象。

realm.executeTransaction((realm) -> {
    // ASSUMING PRIMARY KEY
    Selection selection = realm.where(Selection.class).equalTo(SelectionFields.ID, selectionId).findFirst();
    if(selection == null) {
       selection = realm.createObject(Selection.class, selectionId);
    }
    // here, selection is always managed

    //...
    Product product = realm.where(Product.class)./*...*/.findFirst();
    selection.setProduct(product);

    // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
});

但您也可以设置产品 link 只有在您将代理转为受管后。

realm.executeTransaction((realm) -> {
    Selection selection = new Selection();

    // assuming selection.getProduct() == null

    selection = realm.copyToRealmOrUpdate(selection);
    // selection is now managed

    Product product = realm.where(Product.class)./*...*/.findFirst();
    selection.setProduct(product);

    // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
});

如果您不想存储 Product,那么您可以只在对象中存储它的 ID。如果您将使用 copyToRealmOrUpdate - 您可能会不小心更新您的对象,因为此方法执行深层复制。