Golang Gorm:是否可以通过many2many关系删除记录? [英] Golang Gorm: Is it possible to delete a record via a many2many relationship?

查看:67
本文介绍了Golang Gorm:是否可以通过many2many关系删除记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多结构,类似于GORM的示例:

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.

我从数据库中获取用户记录,并从用户的Languages数组中删除一种语言.然后,我将gorm:save_associations设置为true来保存用户.

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.

我希望GORM删除将用户与该语言相关联的记录(在GORM管理的关联表中).但是,它不会被删除.这是预期的吗?

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?

是否可以通过从用户记录的语言"列表中删除一种语言然后保存用户来删除很多很多关联记录?如果没有,那么在GORM中应该如何做?

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?

更新

我找到了解决这个问题的方法,但是不确定这是最好的方法.我存储了当前的语言,清除了所有关联,然后重新添加了语言,然后保存.

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

推荐答案

我找到了解决此问题的方法,但不确定是否是解决此问题的最佳方法.我存储了当前的语言,清除了所有关联,然后重新添加了语言,然后保存.

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

这篇关于Golang Gorm:是否可以通过many2many关系删除记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆