我在 Flutter 中使用 Firebase 数据库,使用 Flutter 中的 Firestore 包来执行此操作。 我想知道如何在 noSQL 中(或更具体地说,在 Flutter-Firestore 中)完成连接
这是我的数据库的样子:
users: {
U1: {
name: 'Peter',
surname: 'Jensen'
},
U2: {
name: 'Marry',
surname: 'Kown'
},
...
}
groups: {
G1: {
name: 'Group 1'
},
G2: {
name: 'Group 2'
},
...
}
members: {
M1: {
userId: U1,
groupId: G1
},
M2: {
userId: U1,
groupId: G2
},
M3: {
userId: U2,
groupId: G1
},
...
}
现在我如何做一个连接来得到这样的东西:
members: {
M1: {
userId: {
name: 'Peter',
surname: 'Jensen'
},
groupId: {
name: 'Group 1'
}
},
M2: {
userId: {
name: 'Peter',
surname: 'Jensen'
},
groupId: {
name: 'Group 2'
}
},
M3: {
userId: {
name: 'Marry',
surname: 'Kown'
},
groupId: {
name: 'Group 1'
}
},
...
}
我会做吗:
const users = await Firestore.instance.collection('users').getDocuments();
const groups = await Firestore.instance.collection('groups').getDocuments();
const members = await Firestore.instance.collection('members').getDocuments();
...manually loop through everything and assign everything myself
(我需要添加更多文本,因为我有“大部分代码”):我假设以上内容会在 Firebase 中使用大量查询数据,所以我看不出这是个好主意。我实际上只是想看看用户在哪些组中
最佳答案
如果您有群组和成员,我通常会存储以下数据:
users
集合中的用户列表。- 对于每个用户,我会保留他们的属性和他们所属组的组 ID 列表。
groups
集合中的组列表。- 我会为每个小组保留他们的属性(property)
请注意,您可以将嵌套列表建模为子集合,但通常不需要这样做。使用上述模型,您可以轻松找到用户所属的组,甚至可以使用 array-contains
子句查询属于特定组的用户。
要获取特定用户组的属性列表,您确实需要分别加载该用户及其组。这对于许多 NoSQL 数据库来说是正常的,并不一定像您预期的那样慢。但是如果性能不够好,你可以考虑复制一些数据来减少连接的需要。这完全取决于您的需求,与关系数据模型不同,NoSQL 对此类事情并不教条。
要了解有关此主题的更多信息:
关于firebase - Flutter Firestore 理解加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876092/