Gorm: How to create a reference without creation of association itself in many-to-many use case

Created on 14 Oct 2020  路  6Comments  路  Source: go-gorm/gorm

Question

Is it possible to create a reference without creation of association itself in many-to-many use case?

E.g. I have tables - users, languages and joint table user_languages. languages table is already fulfilled with a list of available languages. When I'm creating a user with languages I don't need to do insertion into languages but I want to create a reference in a joint table only. In gorm v1 such behaviour was achieved by using association_autoupdate:false tag in a model. In gorm v2 method Omit("Languages") also omits reference.
Thank you!

feature_request

Most helpful comment

I believe this should be considered as a bug not feature_request

All 6 comments

gorm v2
However, even if Omit("Languages") is used, the INSERT INTO `languages`... statement will still be executed

type User struct {
    Id int
    Languages []Language `gorm:"many2many:language_user"`
}

type Language struct {
    Id int
}

When I run

db.Debug().Model(&User{Id: 1}).Omit("Languages").Association("Languages").Append([]Language{{Id: 9},{Id: 10}})

The console printed these two lines of statements

//INSERT INTO `languages` ...
//INSERT INTO `language_user` ...

INSERT INTO `languages` ... I don鈥檛 want this because I set the verification in the hook of Language

I have the same question

I believe this should be considered as a bug not feature_request

The latest master support to use the following code to skip the associations itself

db.Omit("Languages.*")

Updated the document https://gorm.io/docs/associations.html#Skip-Auto-Create-Update

@jinzhu Is this in a tagged release? I came over from this linked issue - https://github.com/go-gorm/gorm/issues/3710

On 1.20.8 I'm still seeing INSERT INTO "languages" inserts when I'm just wanting the association record in the association table to be created with provided IDs, and for gorm to please leave the resource tables alone when making just an association between two existing records.

db.Debug().Model(&User{Id: 1}).Omit("Languages.*").Association("Languages").Append([]Language{{Id: 9},{Id: 10}})

I'm looking for an api method to ONLY create the language_user association table record.

Actual

INSERT INTO "languages"...

INSERT INTO "language_user"...

Expected (Desired?)

INSERT INTO "language_user"...
Was this page helpful?
0 / 5 - 0 ratings

Related issues

rfyiamcool picture rfyiamcool  路  3Comments

superwf picture superwf  路  3Comments

leebrooks0 picture leebrooks0  路  3Comments

izouxv picture izouxv  路  3Comments

littletwolee picture littletwolee  路  3Comments