"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Define Foreign Key Constraints in Gorm for Go?

How to Define Foreign Key Constraints in Gorm for Go?

Posted on 2025-03-23
Browse:398

How to Define Foreign Key Constraints in Gorm for Go?

How to Establish Foreign Key Constraints Using Gorm

When managing entity relationships in a database using Go, it's essential to establish clear foreign key constraints. In this article, we will explore the process of defining such constraints using Gorm, a popular ORM for Go.

Defining the Models

Consider the following example scenario, where we have two models:

type User struct {
    ID       uint
    Email    string
    Password string
}

type UserInfo struct {
    UID       uint
    FirstName string
    LastName  string
    Phone     string
    Address   string
    User      User // Represents the foreign key relationship
}

In this example, User is the parent table, and UserInfo is the child table. The UID field in UserInfo serves as the foreign key, referencing the ID field in the User table.

Foreign Key using Gorm

In Gorm prior to version 2.0, it was necessary to explicitly create foreign key constraints in the database schema. This is achieved by using the AddForeignKey method in the migration code:

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

Note

However, from Gorm version 2.0 onwards, this manual process is no longer required. Gorm automatically infers foreign key constraints based on the defined relationships between models.

Conclusion

Defining foreign key constraints ensures data integrity and enforces referential integrity between tables. By understanding and applying the appropriate methods in Gorm, you can effectively manage database relationships in your Go applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3