[Vuejs]-Querying and mutating firebase realtime database many to many (two way) relationships

1đź‘Ť

âś…

You have to use the update() method which allows writing “multiple values to the Database at once” (see also here):

Here is an example on how you would do for the first case (“how do I not only add him to the players object, but also to the team_memberships object”).

var userObj = {
    firstName: payload.firstName,
    lastName: payload.lastName,
    jerseyNumber: payload.jerseyNumber,
    teamName: payload.teamName
};

var team_id = '....'  //I don't know how you plan to get this value.

var newPlayerKey = firebase.database().ref('users').child(user.uid).child('players').push().key;

var updates = {};
updates['/users/' + user.uid + '/players/' + newPlayerKey] = userObj;
updates['/users/' + user.uid + '/team_memberships/' + team_id + '/' + newPlayerKey] = true;

return firebase.database().ref().update(updates);

Note: I don’t know how you plan to get the value of team_id but most probably from the front end, since you have the teamName.

👤Renaud Tarnec

Leave a comment