Create reverse query 'has a' relation GORM

WBOY
Release: 2024-02-08 21:08:54
forward
1120 people have browsed it

创建反向查询“有一个”关系 GORM

php Xiaobian Yuzi introduces you to the reverse query in GORM. In GORM, we can implement reverse query by creating a "has a" relationship. In this way, we can easily obtain the information of the related model in the related model. The setting of this relationship can help us process data more efficiently and improve query performance and readability. Whether it's a one-to-one or one-to-many relationship, GORM provides a simple and flexible way to create reverse queries. Next, we'll take a deeper look at how to use the "has a" relationship in GORM to create a reverse query.

Question content


I am currently trying to create a new record using GORM, two models that have a one-to-one relationship with each other. Model1 has a "has a" relationship with Model2. I was wondering if in this case I could create a query for Model2 instead of Model1. Here's an example from the documentation:

So, in the document context, is it possible to create a query from the CreditCard structure, since I want to preserve the "has a" relationship.


Solution


I successfully solved this problem! You just need to include the foreign keys in the structural model when you create 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)
Copy after login

The above is the detailed content of Create reverse query 'has a' relation GORM. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!