如何删除angularfire2中的链接引用?

How to delete linked references in angularfire2?

我有三个模型 City(有多个 Block s),Block(有多个 Area s)和 Area(一对多关系继续到其他模型,这里不显示)。

从图片中您可以看到我已将数据展平并使用 $key 参考。

我的问题是存储此数据的最佳方式是什么以及如何删除所有链接的引用?假设删除一个城市时,应删除所有块的引用以及与块链接的所有区域。

下面是数据结构

我现在用来删除的代码是,不删除区域:

    deleteCity(city: City): void {
      this.af.database.list(`/cities/${city.$key}/blocks`, { preserveSnapshot: true })
                .subscribe(snapshots => {
                    snapshots.forEach(snapshot => {
                          this.af.database.object(`/blocks/${snapshot.key}`).remove();
                        });
              });
       this.af.database.list('/cities').remove(city.$key).then(
            () => this.appstore.dispatch({ type: DELETE_CITY, payload: city})
    );
  }

请对数据设计和删除过程提出建议。

您可能应该做的第一件事是等到块被移除后再移除城市:

import 'rxjs/add/operator/first';
import 'rxjs/add/operator/toPromise';

// Use the first operator to take the first emitted list and then
// complete the observable and use the toPromise operator to
// convert it into a promise for simpler chaining.

deleteCity(city: City): void {
  this.af.database
    .list(`/cities/${city.$key}/blocks`, { preserveSnapshot: true })
    .first()
    .toPromise()
    .then(snapshots => {
      snapshots.forEach(snapshot => {
        this.af.database.object(`/blocks/${snapshot.key}`).remove();
      });
    })
    .then(() => this.af.database.list('/cities').remove(city.$key))
    .then(() => this.appstore.dispatch({ type: DELETE_CITY, payload: city});
);

你也应该对区域做类似的事情。

除此之外,对数据库结构和数据的任何更改都取决于您希望如何访问它。

如果您只需要访问城市上下文中的块和块上下文中的区域并且从不需要访问任意块或区域,您可以包括路径中的城市键:

/areas/$cityKey/$areaKey
/blocks/$cityKey/$blockKey

移除一个城市的所有街区和区域等都是微不足道的。

另一种选择是使用每个块中的 cityKey 子 属性。你可以通过这样的查询获取那些:

this.af.database
  .list(`/blocks`, {
    preserveSnapshot: true,
    query: {
      orderByChild: 'cityKey',
      equalTo: '-KaXa...'
    }
  })

类似地,如果您向区域添加 cityId 个子项,您可以以类似的方式查询这些区域。这至少可以避免获取一个城市的所有街区和每个街区的所有区域;您只需使用城市密钥即可获得所有街区和区域。