Working with relationships
Relational databases are powerful because they allow us to model complex relationships between different entities. GORM makes it easy to define and work with these relationships using struct tags and methods.
So, let’s see some examples of how you deal with relationships in GORM, starting with the creation of related records:
user := User{
Username: "johndoe",
Password: "password123",
Role: "user",
Sessions: []Session{
{
Token: "abc123",
Expires: time.Now().Add(24 * time.Hour),
},
},
}
db.Create(&user) // Creates both user and session
In this case, we are not only creating a user but also, in the same operation, making a session associated with that user. Then, we retrieve that session, as we saw before:
var user User
db.Preload("Sessions").First(&user)
As we saw before, we can automatically populate the user Sessions field using Preload...