duanbenzan4050 2016-07-08 15:16
浏览 352
已采纳

Golang Gorm:是否可以通过many2many关系删除记录?

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 {
    gorm.Model
    Languages         []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
    gorm.Model
    Name string
}

db.Model(&user).Related(&languages)

Let's say I create a user and it has two associated languages.

I fetch a user record from the database and remove one language from the user's Languages array. I then save the user with gorm:save_associations set to true.

I would expect GORM to delete the record associating the user to this language (in the association table that GORM manages). However, it is not deleted. Is this expected?

Is it possible to delete many2many association records by removing a language from the Languages list on the user record and then saving the user? If not, how should this be done in GORM?

Update

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
  • 写回答

3条回答 默认 最新

  • douying9296 2016-07-08 21:15
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?