type User struct { gorm.Model Account string json:"account" gorm:"column:account;type:varchar(30);not null;comment:账号" Password string json:"password" gorm:"column:password;type:varchar(30);not null;comment:密码" Name string json:"name" gorm:"column:name;type:varchar(30);not null;comment:姓名" Avatar string json:"avatar" gorm:"column:avatar;type:varchar(300);comment:头像" Roles []Role gorm:"many2many:user_roles;" }

type Role struct { gorm.Model Name string json:"name" gorm:"column:name;type:varchar(30);not null;comment:角色名称" Permissions []Permission gorm:"many2many:role_permissions;" Users []User gorm:"many2many:user_roles;" }

err = mysqlClient.SetupJoinTable(&User{}, "Roles", &UserRole{}) err = mysqlClient.SetupJoinTable(&Role{}, "Users", &UserRole{})

if err := us.gorm.Model(&models.User{Model: gorm.Model{ ID: userID, }}).Association("Roles").Replace(roles); err != nil { return err }

INSERT INTO user_roles (created_at,updated_at,deleted_at,user_id,role_id) VALUES ('2023-09-07 15:18:44.322','2023-09-07 15:18:44.322',NULL,1,1) ON DUPLICATE KEY UPDATE id=id

Why does it always add a new record instead of replacing it?

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: saeidee

Please read the docs https://gorm.io/docs/associations.html#Replace-Associations

Comment From: Shuzhenzhou

yes,Why does it always add a new record instead of replacing it?

Comment From: saeidee

If you want to delete the old records you can use the Unscope function https://gorm.io/docs/associations.html#Delete-Association-Record.