Many To Many
Many to Many adds a join table between two models.
For example, if your application includes users and languages, and a user can speak many languages, and many users can speak a specified language.
// User has and belongs to many languages, use `user_languages` as join table |
Back-Reference
// User has and belongs to many languages, use `user_languages` as join table |
Foreign Keys
type CustomizePerson struct { |
It will create a many2many relationship for those two structs, and their relations will be saved into join table PersonAccount
with foreign keys customize_person_id_person
AND customize_account_id_account
Jointable ForeignKey
If you want to change join table’s foreign keys, you could use tag association_jointable_foreignkey
, jointable_foreignkey
type CustomizePerson struct { |
Self-Referencing
To define a self-referencing many2many relationship, you have to change association’s foreign key in the join table.
to make it different with source’s foreign key, which is generated using struct’s name and its primary key, for example:
type User struct { |
GORM will create a join table with foreign key user_id
and friend_id
, and use it to save user’s self-reference relationship.
Then you can operate it like normal relations, e.g:
DB.Preload("Friends").First(&user, "id = ?", 1) |
Working with Many To Many
db.Model(&user).Related(&languages, "Languages") |
For advanced usage, refer Association Mode