Create Query 'has one' relationship in reverse direction GORM

huangapple go评论68阅读模式
英文:

Create Query 'has one' relationship in reverse direction GORM

问题

我目前正在尝试使用GORM创建一个新的记录,这两个模型之间有一对一的关系。Model1与Model2之间有一个"has one"的关系。我在想在这种情况下是否可以创建一个从Model2而不是Model1的查询。以下是文档中的一个示例:

Create Query 'has one' relationship in reverse direction GORM

在文档的上下文中,是否可以从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:

Create Query 'has one' relationship in reverse direction GORM

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: &quot;41111111111111&quot;
	UserID: &lt;include the id here&gt; // make sure the credit card gorm model has UserID foreign key specified
}
db.Create(&amp;CreditCard)

huangapple
  • 本文由 发表于 2023年1月3日 22:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/74994891.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定