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.
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.
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)
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!