Firebase 简单的多对多关系 [英] Firebase simple many to many relationship
问题描述
我对 NoSQL 和 Firebase 实时数据库有点熟悉,而且我知道这不是解决关系数据库更合适的任务的最佳解决方案.我想验证我拥有的简单多对多关系的结构.
I am bit familiar with NoSQL and Firebase Realtime Database and also I know that it is not best solution to solve tasks where relational database should be more appropriate. I want to verify about structure of simple many to many relationship that I have.
我有事件和用户.我想使用 Firebase 存储有关用户参与活动的信息,稍后我需要
I have events and users. I want to use Firebase for storing information about users participating in events, later I will need to
- 获取活动用户列表,知道它的 id 和城市
- 获取用户活动列表,了解其 id 和城市
- 添加或删除有关用户参加活动的信息
- Get list of users for event knowing it's id and city
- Get list of events for users knowing it's id and city
- add or delete information about user attending to event
我想要按城市划分的第一个事件 ID 树.
I would like to have first tree of events ids divided by cities.
events {
'city1' : {
event_id_1 : {'user_1', 'user_2'},
event_id_2 : {'user_3', 'user_4'}.
}
'city2' : {
event_id_3 : {'user_5', 'user_6'},
event_id_4 : {'user_7', 'user_7'}.
}
}
用户的第二棵树
users {
'user1' : {
'city1' : {event_id_1, event_id_2},
'city2' : {event_id_3, event_id_4},
'city3' : {event_id_3, event_id_4}
},
'user2' : {
'city1' : {event_id_1, event_id_2},
'city2' : {event_id_3, event_id_4},
'city3' : {event_id_3, event_id_4}
},
'user3' : {
'city1' : {event_id_1, event_id_2},
'city2' : {event_id_3, event_id_4},
'city3' : {event_id_3, event_id_4}
},
}
是否易于使用和维护?
推荐答案
考虑到列出的要求,您的结构在我看来还不错.最重要的是:您已经在两个方向上存储数据,这对于许多刚接触 NoSQL 数据建模的开发人员来说是最大的障碍.
Your structure looks pretty OK to me given the requirements listed. Most importantly: you store the data in both directions already, which is the biggest hurdle for many developers new to NoSQL data modeling.
关于您的数据模型的一些注意事项,尽管大多数都属于拼写错误:
A few notes about your data model, though most are on the level of typos:
- 务必将数据存储为地图,而不是数组.所以
event_id_1 : {'user_1': true, 'user_2': true }
- 如果用户和事件之间存在多对多关系,我通常会有四个顶级列表:
users
和events
(用于主要信息),然后是userEvents
和eventUsers
(用于两者之间的连接).
- Be sure to store the data as maps, not arrays. So
event_id_1 : {'user_1': true, 'user_2': true }
- If there is a many-to-many relationship between users and events, I'd usually have four top-level lists:
users
andevents
(for the primary information about each), and thenuserEvents
andeventUsers
(for connections between the two).
将用户添加到事件可以通过单个多位置更新来完成,例如:
Adding a user to an event can be done with a single multi-location update, e.g.:
ref.update({
'/userEvents/userId1/eventId1': true,
'/eventUsers/eventId1/userId1': true
});
取消注册它们只需使用 null
作为值(删除现有键):
Unregistering them is a matter of doing the same with null
as the value (which deletes the existing key):
ref.update({
'/userEvents/userId1/eventId1': null,
'/eventUsers/eventId1/userId1': null
});
还可以在这里查看我的答案:Firebase 中的多对多关系
Also see my answer here: Many to Many relationship in Firebase
这篇关于Firebase 简单的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!