Many-to-many using Firebase

前端 未结 1 678
抹茶落季
抹茶落季 2020-12-29 10:06

Lets say I have two kinds of objects users and accounts. Users can have many Accounts and share them with other Users. So AccountA might be available to User1 and User2. Whi

相关标签:
1条回答
  • 2020-12-29 11:00

    Before jumping into specifics, there are a few things you'll want to keep in mind:

    1. You'll typically want to structure your data based on your reading patterns. So if you need to look up all accounts a user is in, you'll need to store that list somewhere. And if you want to look up all users associated with an account, you'll need to store that list somewhere as well. So regarding question #2, Firebase doesn't currently have any generic querying ability (like "/accounts[1,2]"), though this will probably come in the future.
    2. Security rules can't be used to query data either. You're either allowed to read all of the data at a location, or none of it. So regarding your question #1, the security rules won't automatically query /accounts for you.
    3. Security rules don't let you search the contents of an array for an element, but they can check for the existence of a key in an object. Therefore if users 1 and 4 have access to something, you'll probably want to store { 1: true, 4: true } rather than [1, 4].

    With that in mind, I'd recommend storing the data like your first example, but without using arrays:

    users: {
      1: {
        name: 'Ted',
        accounts: {
          1: true,
          2: true
        }
      }
      2: {
        name: 'Frank',
        accounts: {
          1: true
        }
      }
    }
    
    accounts: {
      1: {
        name: "Checking"
      },
      2: {
        name: "Savings"
      }
    }
    

    This will let you easily get all of the accounts for a particular user. If you need to also be able to go the other direction (all of the users for an account), you'll have to duplicate that information and store it in the accounts as well. E.g.:

    accounts: {
      1: {
        name: "Checking",
        users: {
          1: true,
          2: true
        }
      },
      2: {
        name: "Savings",
        users: {
          1: true
        }
      }
    }
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题