Home >Backend Development >Golang >How to Create Foreign Key Relationships in GORM (Before and After Version 2.0)?

How to Create Foreign Key Relationships in GORM (Before and After Version 2.0)?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 12:41:15812browse

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:

  • The first argument, "u_id", represents the foreign key field in the secondary model (UserInfo).
  • The second argument, "t_user(id)", specifies the table and field in the primary model (User).
  • The third and fourth arguments, "RESTRICT", define the behavior when the primary key is updated or deleted. In this case, it will restrict the operation.

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!

Statement:
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