Thursday, 10 December 2020

How do i traverse a children table that have relationship with multiple tables

How do i traverse the child book table when i pass the grandparent_id or parent_id to look up all the related books both in parent book and child book tables. I'm guessing it is more of a data structure problem. I'm using Activerecord to fetch the data from the database.

Tables structure

grand_parent_category

Id      name
2       Math

parent_category

Id      name
1   Algebra book

child_category

Id     name            parent_id.    grandparent_id.   
1.      Calculus book    1                 2

The normal way is to traverse the entire child books array and search the grandparent_id in the book column.

it would be the same if i choose parent_id

Example

@child_books = child_books.all()

Im passing the @child_books object to the frontend via Gon

Javascript

gon.child_books.forEach((book) => {
   If (book.grandparent_id == chosen_grandparent_id) {
      // do something
    } else if book.parent_id == chosen_parent_id {
      // do something
    } else if book.parent_id == children_id
});

The result would be. If I choose grandparent_id book. Math

  1. Grandparent = Math

  2. Parent = Algebra, Calculus

  3. Children = Additional Math, Discrete Math

    Math

    /

    Algebra

    / \

    Additional Math Discrete math

But this approach is really slow, if the dataset for child book category is huge let say 5000. Then in order to find the relationship I have to traverse one by one

Another approach I was thinking is to use hash

@child_books = child_books.all()
@child_books.index_by(&:id)

This will give this result

 {
          
      1: {id: 1, name: “additional mathematics”, parent_id: 1, grandparent_id: 2 }
      2: {id: 2, name: “discrete mathematics”, parent_id: 1, grandparent_id: 2 }
        
  }

But this approach can’t be done if I pass the grandparent_id to search for both parent and children books.

What approach should tackle this relationship problem.



from How do i traverse a children table that have relationship with multiple tables

No comments:

Post a Comment