0

Having issues with many2many, I went back to the documentation and tried to make the first example work.

// User has and belongs to many languages, `user_languages` is the join table
type User struct {
  gorm.Model
  Languages []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
  gorm.Model
  Name string
}

gorm-playground has similar code so I just had to slightly modify models.go with

type Language struct {
    gorm.Model
    Code string
    Name string
}

and main_test.go by adding

DB.Model(&result).Association("Languages").Append(&Language{
    Code: "en-us",
    Name: "English",
})

at the end of TestGORM.

I tested with mysql, postgres & sqlite. It went great.

Then I duplicated the code in TestGORM to add a second user speaking the same language.

a) as is, I ended up (same test matrix: mysql, postgres & sqlite) with 2 identical Language records which is not what I expected.

b) so I added a gorm annotation to Code => gorm:"size:64;uniqueIndex" This time, gorm asked the db to INSERT ... ON CONFLICT DO NOTHING RETURNING id (postgres & sqlite), ON DUPLICATE KEY UPDATE id=id (mysql).

But then trying to create the join table record, the db sets language_id to 0 (the original en-us record being id=1) which expectedly failed (FOREIGN KEY constraint).

I'd love to know what I'm missing as I'm out of ideas. It feels like gorm isn't getting id back after the "insert conflict".

1 Answer 1

0
func (u *user) BeforeCreate(tx *gorm.DB) error {
    if b.Id == "" {
        u.Id = util.Uuid()
    }
}

may be useful

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.