How to Create a Foreign Key Relationship with GORM in Go?

Susan Sarandon
Release: 2024-11-22 03:50:15
Original
470 people have browsed it

How to Create a Foreign Key Relationship with GORM in Go?

Creating Foreign Key Relationships with Gorm

Problem:
Your Go application utilizes two models, User and UserInfo, and you desire to establish a foreign key relationship between the UID field in UserInfo and the id field in User. Modifying the UserInfo model alone has proven ineffective.

Solution:

Instead of relying solely on the gorm annotations in the UserInfo model, you can define the foreign key constraint during database migration. Add the following line to your migration script:

db.Model(&models.UserInfo{}).AddForeignKey("u_id", "t_user(id)", "RESTRICT", "RESTRICT")
Copy after login

This line accomplishes the following:

  • It specifies that the u_id field in UserInfo is a foreign key associated with the id field in the t_user table.
  • It sets the ON DELETE and ON UPDATE actions to RESTRICT, meaning that any attempt to delete or update a user row will be rejected if there are any existing UserInfo rows referencing it.

The above is the detailed content of How to Create a Foreign Key Relationship with GORM in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template