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
Declare
// User has and belongs to many languages, use `user_languages` as join table |
Retrieve
// Retrieve user list with eager loading languages |
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
, references
, joinForeignKey
, joinReferences
, not necessary to use them together, you can just use one of them to override some foreign keys/references
type User struct { |
NOTE:
Some databases only allow create database foreign keys that reference on a field having unique index, so you need to specify theunique index
tag if you are creating database foreign keys when migrating
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 more fields, you can set it up with SetupJoinTable
, for example:
NOTE:
Customized join table’s foreign keys required to be composited primary keys or composited unique index
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 { |
You are also allowed to delete selected many2many relations with Select
when deleting, checkout Delete with Select for details
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