Golang Gorm: Is it possible to delete a record via a many2many relationship?

后端 未结 3 2075
不知归路
不知归路 2021-02-20 14:31

I have a many2many structure similar to GORM\'s example:

// User has and belongs to many languages, use `user_languages` as join table
type User struct {
    gor         


        
相关标签:
3条回答
  • 2021-02-20 14:51

    I was having the same problem, If you want to just remove one of the associations this worked for me

        c.DB.Model(&user).Association("Roles").Delete(&role)
    
    0 讨论(0)
  • 2021-02-20 14:51

    I found a solution to this question, but not sure it's the best way to do this. I store the current languages, clear all the associations, then add back the languages, then save.

    languages := user.Languages 
    DB.Model(&user).Association("Languages").Clear()
    user.Languages = languages
    
    0 讨论(0)
  • 2021-02-20 14:56

    Also, you can do this by using "replace"

    DB.Model(&user).Association("Languages").Replace(user.Languages)
    
    0 讨论(0)
提交回复
热议问题