英文:
Create Query 'has one' relationship in reverse direction GORM
问题
我目前正在尝试使用GORM创建一个新的记录,这两个模型之间有一对一的关系。Model1与Model2之间有一个"has one"的关系。我在想在这种情况下是否可以创建一个从Model2而不是Model1的查询。以下是文档中的一个示例:
在文档的上下文中,是否可以从CreditCard结构中创建查询,因为我想保持"has one"的关系。
英文:
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:
So in the docs context, is it possible to create query from the CreditCard struct as I want to persist the 'has one' relationship.
答案1
得分: 0
我成功解决了!在创建结构模型时,你可以直接在其中包含外键。例如:
CreditCard{
Number: "41111111111111"
UserID: <在这里包含用户ID> // 确保信用卡gorm模型指定了UserID外键
}
db.Create(&CreditCard)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论