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}
},
}
使用和维护会容易又快速吗?
Would it be easy and fast to use and maintain?
推荐答案
给定列出的要求,您的结构对我来说还不错.最重要的是:您已经在两个方向上存储了数据,这对于许多刚接触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屋!