SoFunction
Updated on 2025-03-04

Golang Gorm's relationship implementation example

1. Related

1.1. Belongs to

// `User` belongs to `Profile`, `ProfileID` is a foreign keytype User struct {
  
  Profile   Profile
  ProfileID int
}
type Profile struct {
  
  Name string
}
(&user).Related(&profile)
///// SELECT * FROM profiles WHERE id = 111; // 111 is the foreign key ProfileID of user

Specify a foreign key

type Profile struct {
    
    Name string
}
type User struct {
    
    Profile      Profile `gorm:"ForeignKey:ProfileRefer"` // Use ProfileRefer as a foreign key    ProfileRefer int
}

Specify foreign keys and associated foreign keys

type Profile struct {
    
    Refer string
    Name  string
}
type User struct {
    
    Profile   Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
    ProfileID int
}

1.2. Contains one

// User contains a CreditCard, UserID is a foreign keytype User struct {
    
    CreditCard   CreditCard
}
type CreditCard struct {
    
    UserID   uint
    Number   string
}
var card CreditCard
(&user).Related(&card, "CreditCard")
//// SELECT * FROM credit_cards WHERE user_id = 123; // 123 is user's primary key
// CreditCard is the field name of user, which means getting the CreditCard relationship of user and populating it into the variable// If the field name is the same as the type name of the variable, as shown in the above example, it can be omitted, such as:(&user).Related(&card)

Specify a foreign key

type Profile struct {
  
  Name      string
  UserRefer uint
}
type User struct {
  
  Profile Profile `gorm:"ForeignKey:UserRefer"`
}

Specify foreign keys and associated foreign keys

type Profile struct {
  
  Name   string
  UserID uint
}
type User struct {
  
  Refer   string
  Profile Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
}

1.3. Contains multiple

// User contains multiple emails, UserID is a foreign keytype User struct {
    
    Emails   []Email
}
type Email struct {
    
    Email   string
    UserID  uint
}
(&user).Related(&emails)
///// SELECT * FROM emails WHERE user_id = 111; // 111 is the primary key of user

Specify a foreign key

type Profile struct {
  
  Name      string
  UserRefer uint
}
type User struct {
  
  Profiles []Profile `gorm:"ForeignKey:UserRefer"`
}

Specify foreign keys and associated foreign keys

type Profile struct {
  
  Name   string
  UserID uint
}
type User struct {
  
  Refer   string
  Profiles []Profile `gorm:"ForeignKey:UserID;AssociationForeignKey:Refer"`
}

1.4. Many-to-many

// User contains and belongs to multiple languages, join using the `user_languages` tabletype User struct {
    
    Languages         []Language `gorm:"many2many:user_languages;"`
}
type Language struct {
    
    Name string
}
(&user).Related(&languages, "Languages")
//// SELECT * FROM "languages" INNER JOIN "user_languages" ON "user_languages"."language_id" = "languages"."id" WHERE "user_languages"."user_id" = 111

Specify foreign keys and associated foreign keys

type CustomizePerson struct {
  IdPerson string             `gorm:"primary_key:true"`
  Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;ForeignKey:IdPerson;AssociationForeignKey:IdAccount"`
}
type CustomizeAccount struct {
  IdAccount string `gorm:"primary_key:true"`
  Name      string
}

Translator's note: Some of the settings seem to be missing

1.5. Various Inclusions

Supports multiple associations including one and multiple

type Cat struct {
    Id    int
    Name  string
    Toy   Toy `gorm:"polymorphic:Owner;"`
  }
  type Dog struct {
    Id   int
    Name string
    Toy  Toy `gorm:"polymorphic:Owner;"`
  }
  type Toy struct {
    Id        int
    Name      string
    OwnerId   int
    OwnerType string
  }

Note: Polymorphic properties and many-to-many explicit are not supported and errors are thrown.

1.6. Association mode

It's easy to have a correlation pattern that contains some help methods to handle relationship things.

// Start the association modevar user User
(&user).Association("Languages")
// `user` is the source, it needs to be a valid record (including the primary key)// `Languages` is the field name of the source in the relationship.// If these conditions do not match, an error will be returned, check it:// (&user).Association("Languages").Error
// Query - Find all related relationships(&user).Association("Languages").Find(&languages)
// Append - Adding a new many2many, has_many association will replace the current has_one, belongs_to association(&user).Association("Languages").Append([]Language{languageZH, languageEN})
(&user).Association("Languages").Append(Language{Name: "DE"})
// Delete - Delete the relationship between the source and passed parameters, and will not delete these parameters(&user).Association("Languages").Delete([]Language{languageZH, languageEN})
(&user).Association("Languages").Delete(languageZH, languageEN)
// Replace - Replace the current association with new association(&user).Association("Languages").Replace([]Language{languageZH, languageEN})
(&user).Association("Languages").Replace(Language{Name: "DE"}, languageEN)
// Count - Returns the current associated count(&user).Association("Languages").Count()
// Clear - Delete the relationship between the source and the current association, and will not delete these associations(&user).Association("Languages").Clear()

The above is the detailed content of the relationship association implementation example of golang gorm. For more information about golang gorm's relationship association, please pay attention to my other related articles!