2

The following is my database design in firebase

- Sports
  - MainCategory (hypothetical category name)
    - SubCategory1
      - K_tgbBt6Vx0-kkg7e63
        - name:football
      - K_tgbBt6Vx0-kkg7a99
        - name:golf
     - Subcategory2
      - K_tgbBt6Vx0-kkgad21
        - name:Snooker
      - K_tgbBt6Vx0-kkg7e00
        - name:Table Tennis
  - MainCategory2
     - SomeOtherSubCategory1
      -K_tgbBt6Vx0-kkg7e00

My Aim: To get all the sports under the sports node and display them category wise(i.e MainCategory and Sub category) in a uicollectionview and allow the user to select sports of his choice.

Eg. display

Main Category1

SubCategory1

Football, Golf

SubCategory2

Table Tennis, Snooker

Main Category2

SomeOtherSubCategory1

Hockey,Tennis

The following approaches only take me one level deeper in the node

rootref.child("sports").observe(.value, with: { (snapshot) in

    let mainCategory = snapshot.key    
    for child in snapshot.children{
        print(child)
    }})



    rootref.child("sports").observe(.childAdded, with: { (snapshot) in


        let mainCategory = snapshot.key
        let mySnapshot = snapshot.value! as! NSDictionary


    }) { (error) in
        print(error.localizedDescription)
    }

Also if there is any other way i could structure my database, kindly let me know

0

4 Answers 4

1
`rootref.child("sports").observe(.value, with: { (snapshot) in
    //This gets your mainCategory names
    let mainCategory = snapshot.key    
    for child in snapshot.children{
        print(child)
    }})



    rootref.child("sports").observe(.childAdded, with: { (snapshot) in


        let mainCategory = snapshot.key
        let mySnapshot = snapshot.value! as! NSDictionary


    }) { (error) in
        print(error.localizedDescription)
    }

//Now what you need to do is another snapshot to get the sub categories. It would be something like this:

rootref.child("sports").child("Sub-Category").observe(.value, with: { (snaps) in
   //Same steps as you did above
})

`

Sign up to request clarification or add additional context in comments.

Comments

1

It's cool to know that a man like you with 2.5k reps is asking such a question. I assume you know MVC, of course in the future, you'd want a reusable Service Class to handle Firebase requests and Model Class to handle the data.

Next, you should know the different ways of observing data on Firebase. There is a Single Event and Event of Type. Read the doc: https://firebase.google.com/docs/database/ios/read-and-write

In structuring your database, Firebase has a doc for that too: https://firebase.google.com/docs/database/web/structure-data

Anyway, I made a sample for you, take a look: http://www.jsoneditoronline.org/?id=5d9e7067883a538746ace7cdd9e81ebb

I made a new structure, which I believe a better structure, of your databse using jsoneditoronline website. Avoid so much nested nodes as much as possible. See my sample, I made necessary new nodes for faster and easier fetching of data. For example, if you're going to view the link above and download the database and upload it to your Firebase Database, you'll see the structure like so:

enter image description here

As you can see, I have here a parent node called subcategories-sportId, which has child nodes of different subcategories and each of that subcategories, we have the ids of the sports.

Another example, if we would like to get all the sports under subcategory2, we won't be using the data inside our sport node. (see below pic) But instead, we will check the data inside the subcategories-sportid node. Get a reference to that node plus add a child node of the specific subcategory string, then fetch all the sportsIds. Enumerate the sportsIDs and lastly fetch the main data of each sports.

enter image description here

But if we would like to get all the subcategories and main categories of the specific sports, we can use the data inside our sport node (see the above pic)

1 Comment

well learning never stops, i'm failry new to firebase and ios development! I'm taking a while getting my head around duplicating data.
1
  let cat3 = db.child("API Questions").child("Category3").child("Name")
    cat3.observe(FIRDataEventType.value, with:
        { (snapshot) in
            let eventDataloc = snapshot.value as? [String: AnyObject] ?? [:]

           // self.Cat3Qarray.removeAllObjects()

            for (_, value) in eventDataloc
            {
                let studsmodel = FirebaseStructureCustVM.updateQuestionData(Questiondata: value as![String:Any])
                self.Cat3Qarray.add(studsmodel)
                //print(studsmodel)
            }

            self.tableview1.reloadData()


//print snapshot here

    })

4 Comments

Please add some text to explain the code snippet above and help explain how the code solves the problem for the OP
Its ma pleasure to explain In the API Questions is the root and the Category3 is the node of the root again it has a child with a Name so that In your case by using this you can print the deeper in the node how much you want.........if you want to print still deeper into the node in the sense just you need to add let cat3 = db.child("API Questions").child("Category3").child("Name").child("name of child you want")
let cat3 = db.child("APIQuestions").child("Category3").child("Name").child("name of child you want") cat3.observe(FIRDataEventType.value, with: { (snapshot) in let eventDataloc = snapshot.value as? [String: AnyObject] ?? [:] for (_, value) in eventDataloc { let studsmodel = FirebaseStructureCustVM.updateQuestionData(Questiondata: value as![String:Any]) } print("the snap shot of the node is = (snapshot)") }) //by printing snapshot you can get all the node data in the console if you have doubt please ask and if any suggestion please well come
you should update your answer with the explanation so the answer is easier to understand. reading code in the comments here is very difficult. The more detail you can give in your answer, the better it will be and easier for the OP and other viewers to understand.
1

enter image description here In the below, the "API Questions" is the "root" and the "Category1" is the "child" of that root if we want to get the "Category1" data such as MaxMarks:"20",Q:"General information",Qid:"Question 1" so you can print the snapshot like this === print("the snap of the cat1 = (snapshot)") === you will get all the data which is inside of the Category1

        let cat2 = db.child("API Questions").child("Category1")
    cat2.observe(FIRDataEventType.value, with:
        { (snapshot) in
            let eventDataloc = snapshot.value as? [String: AnyObject] ?? [:]



            for (_, value) in eventDataloc
            {
                let studsmodel = FirebaseStructureCustVM.updateQuestionData(Questiondata: value as![String:Any])

            }

           print((snapshot))
                   })

2 Comments

Please add some context to your answer for clarity.
In the above, the "API Questions" is the "root" and the "Category1" is the "child" of that root if we want to get the "Category1" data such as MaxMarks:"20",Q:"General information",Qid:"Question 1" so you can print the snapshot like this === print("the snap of the cat1 = (snapshot)") === you will get all the data which is inside of the Category1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.