在 Realm 上删除父级时删除子级 [英] Deleting children on deleting parent on Realm

查看:90
本文介绍了在 Realm 上删除父级时删除子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道该领域的工作方式类似于 mongodb.我的问题是,如果我想删除孩子和他们的孩子(基本上是从我要删除的节点开始的整个数据分支)怎么办?

I understand that the realm works similar to mongodb. My question is, what if I want to delete the children and their children (basically the whole branch of data starting from the node I am deleting)?

这个问题让我深入了解了领域中的关系如何运作.但我还是一头雾水.

This question gave me some insights on how relationships work in realm. But I am still confused.

推荐答案

Realm 尚不支持级联删除.在支持此功能之前,您需要手动删除子对象.类似以下内容可能有效:

Cascading deletes are not yet supported in Realm. Until this feature is supported you need to delete child objects manually. Something like the following might work:

function deleteObjectGraph(object, type, realm) {
    let objectSchema = realm.schema.find((objectSchema) => objectSchema.name == type);

    // delete all child objects
    for (let propName in objectSchema.properties) {
         let prop = objectSchema.properties[propName];

         // for list properties delete all elements and their children
         if (prop.type == 'list') {
             object[propName].forEach((listObject) =>
                 deleteObjectGraph(listObject, prop.objectType, realm);
             );
         }

         // for object properties delete object and all children
         if (prop.type == 'object' && object[propName] != null) {
             deleteObjectGraph(object[propName], prop.objectType, realm);
         }
    }

    // delete the object
    realm.delete(object);
}

我尚未对此进行测试,这不适用于圆形对象图,或者在重复使用对象的情况下可能会出现问题.

I have not tested this and this will not work for circular object graphs or may have issues in cases where objects are reused.

这篇关于在 Realm 上删除父级时删除子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆