Search code examples
goormgo-gormgo-gin

Create Query 'has one' relationship in reverse direction GORM


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.


Solution

  • 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)