2

I am currently trying to create a new record using GORM and these two models has a one to one relationship with each other. Model1 has 'has one' relationship with Model2. I was thinking if it is possible to create query Model2 instead of Model1 in this case. Here is an example from the docs:

enter image description here

So in the docs context, is it possible to create query from the CreditCard struct as I want to persist the 'has one' relationship.

jmsandiegoo
  • 413
  • 4
  • 14
  • 1
    Can you explain more? What is your expectation from the query? what is the input and output of query? – Amin Rashidbeigi Jan 03 '23 at 15:26
  • @AminRashidbeigi Oh I simply wanted to create CreditCard struct instead of creating User with a nested CreditCard in it. Hence 'reverse direction' – jmsandiegoo Jan 04 '23 at 06:35

1 Answers1

0

I managed to solve it! You can simply just include the foreign key in the struct model when creating it. For example:

CreditCard{
    Number: "41111111111111"
    UserID: <include the id here> // make sure the credit card gorm model has UserID foreign key specified
}
db.Create(&CreditCard)
jmsandiegoo
  • 413
  • 4
  • 14