How to inner-join in firestore

前端 未结 1 1595
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 23:58

I want to build a view to show some events inside a listview in my app like this:

I have these two tables:

Users

相关标签:
1条回答
  • 2020-12-07 00:50

    As I was telling in the coments Firestore does not support multi collection querys cause its no relational DB. If you need to access multiple collections you would manage querys independently.

    This is how I usually get related collections data (Sorry this is JS code but I dont know DART):

        var data = {};
    
        //First you get users data
        DocumentReference document = Firestore.collection("users")
    
        document.get().then((snapshot) => {
    
            //In this case I will store data in some object, so I can add events as an array for a key in each user object
    
            snapshot.forEach((userDoc) => {
                var userDocData = userDoc.data()
    
                if (data[userDoc.id] == undefined) {
                    data[userDoc.id] = userDocData
                }
    
            })
    
            //So in this moment data object contains users, now fill users with events data
    
    //In this var you count how many async events have been downloaded, with results or not.    
    var countEvents = 0
    
            Object.keys(data).forEach((userDocId) => {
    
        //Here Im creating another query to get all events for each user
    
                SnapshotReference eventsForCurrentUserRef = Firestore.collection("events").where("userId", "==", userDocId)
    
                eventsForCurrentUserRef.get.then((eventsForUserSnapshot) => {
    //Count events
    countEvents++
    
                    eventsForUserSnapshot.forEach((eventDoc) => {
    
                        var eventDocData = eventDoc.data()
    
                        //Check if array exists, if not create it
                        if (data[eventDocData.userId].events == undefined) {
                            data[eventDocData.userId].events = []
                        }
    
                        data[eventDocData.userId].events.push(eventDocData)
    
    
                    })
    
    if(countEvents == Object.keys(data).length){
    //Lookup for events in every user has finished
    }
    
                })
    
    
            })
    
        })
    
    0 讨论(0)
提交回复
热议问题