Reputation: 105
I have this models, many-to-many, and I'd like to get all the Gifs that matches a list of Tags.
type Tag struct {
ID uint `gorm:"primary_key" json:"id,omitempty"`
Name string `gorm:"not null;unique" json:"name,omitempty"`
}
type Gif struct {
ID uint `gorm:"primary_key" json:"id,omitempty"`
Url string `gorm:"not null;unique" json:"url,omitempty"`
Tags []Tag `gorm:"many2many:gif_tags;" json:"tags,omitempty"`
}
I prepared a playground here.
If I have an array of Tags containing tag1
and tag2
, I'd like to get gif1
and gif2
in &gifs
.
I read the documentation many times and found only the opposite of my question, i.e. fetching the tags for a given gif.
Do I need to change my models?
Is it possible to set up two Associations fields in a many-to-many relation?
Upvotes: 1
Views: 2242
Reputation: 105
So I found how to add back-reference.
I created two files in the same package containing the models, and added Associations with the same join-table for the many2many
.
tag.go
:
type Tag struct {
ID uint `gorm:"primary_key" json:"id,omitempty"`
Name string `gorm:"not null;unique" json:"name,omitempty"`
Gifs []Gif `gorm:"many2many:gif_tags;" json:"gifs,omitempty"`
}
and gif.go
:
type Gif struct {
ID uint `gorm:"primary_key" json:"id,omitempty"`
Url string `gorm:"not null;unique" json:"url,omitempty"`
Tags []Tag `gorm:"many2many:gif_tags;" json:"tags,omitempty"`
}
They need to be in separate files.
Now I can access easily all the gifs matching a Tag and vice-versa.
Upvotes: 2