Home >Backend Development >Golang >How to Create Foreign Key Relationships in GORM (Before and After Version 2.0)?
Creating Foreign Keys with GORM
Creating foreign key relationships in GORM involves specifying the association foreign key, which links the foreign key in the secondary model to the specific field in the primary model.
Problem:
In the given scenario, the User and UserInfo models are intended to have a foreign key relationship, with UID in UserInfo referencing the id field in User. However, the code attempt to create these foreign key associations appears to be unsuccessful.
Solution:
To establish the foreign key relationship, you can utilize GORM's AddForeignKey method:
db.Model(&models.UserInfo{}).AddForeignKey("u_id", "t_user(id)", "RESTRICT", "RESTRICT")
Explanation:
Note:
This solution applies to GORM versions before 2.0. For GORM 2.0 and above, foreign key constraints are automatically added when defining the relationship.
The above is the detailed content of How to Create Foreign Key Relationships in GORM (Before and After Version 2.0)?. For more information, please follow other related articles on the PHP Chinese website!