Your Question

gorm ver.: gorm.io/gorm v1.23.4 golang ver.: go1.17

Hi, I met a question when I use Many2Many relationship. First, the model is defined like this:

type User struct {
    Model
    ID         int64 `gorm:"primary_key"`
    Name       string
    Age        int
    CompanyID  int64
    Company    Company
    CreditCard []CreditCard
    Language   []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
    Model
    ID    int64 `gorm:"primary_key"`
    Name  string 
    Users []User `gorm:"many2many:user_languages;"`
}

type UserLanguages struct {
    Model
    ID         int64 `gorm:"primary_key"`
    UserID     int64 `gorm:"primary_key"`
    LanguageID int64 `gorm:"primary_key"`
}

the model User and Language are many2many relationship, and the join table is user_languages(I didn't use foreign keys constraints), and now I want to create two users like this:

func CreateUsers() {
    user1 := User{
        Name:       "u1",
        Language:   []Language{
            {Name: "ZH"},
            {Name: "EN"},
        },
    }
    user2 := User{
        Name:       "u1",
        Language:   []Language{
            {Name: "ZH"},
        },
    }

    db.Create(&user1)
    db.Create(&user2)
}

So the problem is here: in the join table user_languages,:

id create_time update_time name
1 1650101206 1650101206 ZH
2 1650101206 1650101206 EN
3 1650101206 1650101206 ZH

there are two records with the same name "ZH", because both user1 and user2 have the language ZH.

The document you expected this should be explained

Expected answer

So I want to ask:

Is there a mechanism to keep only one record if it needs to be referenced by multiple different models Instead of creating duplicate records?

Thanks.

Comment From: eurake

对比Django 的发现 创建的关系表有id, rid1, rid2 id 为AUTO_INCREMENT;
rid1, rid2 为UNIQUE KEY rid1 外键1 约束 rid2 外键2 约束 尝试在 many to many 的上怎么加上约束与外键都加不上

Comment From: StandardStudent

同问,在创建如上结构后, 使用save方法,会在关联表中新增一条关联数据。 期望是能够自动替换关联

Comment From: m430

same problem. How to auto update the join table records?

Comment From: a631807682

https://gorm.io/docs/many_to_many.html#Customize-JoinTable