【问题标题】:How to create a nested folder-like structure in realm react-native?如何在领域 react-native 中创建嵌套的类似文件夹的结构?
【发布时间】:2017-01-26 01:32:19
【问题描述】:

我正在尝试创建一个领域数据库,其中 items 嵌套在 containers 中。这将像标准文件系统一样运行,其中容器可以在其中包含项目和其他容器。如何创建这种类型的结构?我已经设置了这些架构:

const ItemSchema = {
    name: 'Item',
    primaryKey: 'id',
    properties: {
        id:         {type: 'string', indexed: true},
        title:      'string',
        createdAt:  'date',
        updatedAt:  'date',
        picture:    {type: 'data', optional: true},
        parent:     {type: 'Container', optional: true},
    }
};
const ContainerSchema = {
    name: 'Container',
    primaryKey: 'id',
    properties: {
        id:         {type:'string', indexed:true},
        title:      'string',
        createdAt:  'date',
        updatedAt:  'date',
        parent:     {type: 'Container', optional: true},
        childContainers: {type: 'list', objectType: 'Container'},
        childItems: {type: 'list', objectType: 'Item'},
    }
};

我也为 Items 设置了这个模型,但还没有为 Containers 创建一个模型:

class ItemModel {
    constructor(title, children) {
        this.id = Utils.guid();
        this.title = title;
        this.children = children;
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }
}

现在我如何实际填充数据库并将父母和孩子分配给现有项目?我知道我必须这样做才能创建一个项目:

let item = new ItemModel('testItem')
db.write(() => {
            item.updatedAt = new Date();
            db.create('Item', item);
        })

但我不知道在那之后我会去哪里。领域文档给出了这个例子:

carList.push({make: 'Honda', model: 'Accord', miles: 100});

但是一旦我使用db.create 创建了一个容器,我该如何添加一个现有项目作为它的子项(而不是像文档显示的那样声明一个新项目)?

【问题讨论】:

    标签: react-native realm realm-mobile-platform


    【解决方案1】:

    创建项目后,您可以使用push() 将其添加到容器中的列表中。

    假设您已经拥有容器,代码可能如下所示:

    let item = new ItemModel('testItem')
    db.write(() => {
            item.updatedAt = new Date();
            var item = db.create('Item', item);
            container.childItems.push(item);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      相关资源
      最近更新 更多