ElvisBoss
ElvisBoss

Reputation: 199

Database Structure in Firebase

How can I create a structure where a game is link to 2 players? For example, if I create a ping pong game and after the game I want to keep the score and the players. How can I do that? How can I link the 2 players into one game and know what player won and which one lost?

I did something similar in SQL but I do not know how to do it in JSON (Firebase) for Android. In SQL, I created a users table and a games tables and I logged player 1 and player 2 with their user name and then do a SELECT with what player won and which one lose.

How can i do this in Firebase?

Thanks!

Upvotes: 1

Views: 674

Answers (1)

Caleb
Caleb

Reputation: 2298

With NoSQL the data is flattened and duplicated where needed for quick access to relevant data. This is called denormalization which you can read up more in this great post.

So the ping pong game post you provided, your firebase JSON database might look something like this:

players: {
  -KUQvO_GBh4jdale6Pj4: {
    name: 'Hillary',
    wins: 2,
    lost: 0,
    tied: 0,
    gamesPlayed: [
      -KUQvQhApOLfhl0yzTTH,
      -KUQwI4P9q4DdSsUn9Du
    ]
  },
  -KUQvQ3_--kO67AOgc9D: {
    name: 'Trump',
    wins: 0,
    lost: 2,
    tied: 0,
    gamesPlayed: [
      -KUQvQhApOLfhl0yzTTH,
      -KUQwI4P9q4DdSsUn9Du
    ]
  }
},
games: {
  -KUQvQhApOLfhl0yzTTH: {
    player1: -KUQvO_GBh4jdale6Pj4,
    player2: -KUQvQ3_--kO67AOgc9D,
    winner: player1,
    timestamp: 1476863790
  },
  -KUQwI4P9q4DdSsUn9Du: {
    player1: -KUQvO_GBh4jdale6Pj4,
    player2: -KUQvQ3_--kO67AOgc9D,
    winner: player1,
    timestamp: 1476863999
  }
}

UPDATE

This article talks about multiple-location updates that allows you to make simultaneous updates to multiple paths to preserve data integrity. If you make each update individually, there is a chance that one or more might fail, which then means that your data might mean it's out of whack.

Upvotes: 1

Related Questions