When to use both BelongsTo and HasMany?

68 views Asked by At

I use an ORM in Golang (GORM) and I am trying to understand if (and when) I should use both HasMany and BelongsTo relationships.

I understand that using:

  • HasMany allows me to query the children elements from the level of the parent
  • BelongsTo is the other way round, where I can query the parent of a child element

Is there a case where it is needed or recommended to have both relationships? (given that they are redundant)

1

There are 1 answers

0
Nitigya Jain On
  • hasMany means a parent can have 0, 1 or more children. Parent or children can exist indedependtly.

  • belongsTo means a child belongs to exactly 1 parent. Child cannot exist without parent. Although, parent can still exist independently.

It have be helpful where we have some complex queries involved. Generally, onetoone and onetomany can be handled easily by any one of them. But, we can make our db query more efficient by utilizing both of them.

For example, User and CreditCard : A user can have multiple credit cards, a credit card belongs to a single user.

User (id uuid, credit_cards []CreditCards)

CreditCard(id uuid, user_id uuid, user User)

Query -> Get all credit cards of a user with id = uid.

  • Way 1: Traverse CreditCard table with condition userId = uid and return all.

  • Way 2: As we are also having hasMany, we can directly query in User table with id = uid and return CreditCards. It may be more efficient.