Many To Many
Many to Many add 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, `user_languages` is the join table |
When using GORM AutoMigrate
to create a table for User
, GORM will create the join table automatically
Back-Reference
// User has and belongs to many languages, use `user_languages` as join table |
Override Foreign Key
For a many2many
relationship, the join table owns the foreign key which references two models, for example:
type User struct { |
To override them, you can use tag foreignKey
, reference
, joinForeignKey
, joinReferences
, not necessary to use them together, you can just use one of them to override some foreign keys/references
type User struct { |
Self-Referential Many2Many
Self-referencing many2many relationship
type User struct { |
Eager Loading
GORM allows eager loading has many associations with Preload
, refer Preloading (Eager loading) for details
CRUD with Many2Many
Please checkout Association Mode for working with many2many relations
Customize JoinTable
JoinTable
can be a full-featured model, like having Soft Delete
,Hooks
supports, and define more fields, you can setup it with SetupJoinTable
, for example:
type Person struct { |
FOREIGN KEY Constraints
You can setup OnUpdate
, OnDelete
constraints with tag constraint
, it will be created when migrating with GORM, for example:
type User struct { |
Composite Foreign Keys
If you are using Composite Primary Keys for your models, GORM will enable composite foreign keys by default
You are allowed to override the default foreign keys, to specify multiple foreign keys, just separate those keys’ name by commas, for example:
type Tag struct { |
Also check out Composite Primary Keys