【问题标题】:Gorm Association Delete does not remove rows, instead update rowsGorm Association Delete 不会删除行,而是更新行
【发布时间】:2022-11-03 16:23:00
【问题描述】:

一个客户有很多角色。删除客户端后,我想删除所有角色。

 type Client struct {
        Id                          string `gorm:"primaryKey"`
        CreatedAt                   time.Time
        UpdatedAt                   time.Time
        Roles [] Role
    }
    
    type Role struct {
        Id        uint `gorm:"primarykey"`
        CreatedAt time.Time
        UpdatedAt time.Time
    
        ClientID string
    }
    
    return db.Transaction(func(tx *gorm.DB) error {
            err = db.Model(&clientToRemove).Association("Roles").Delete(&clientToRemove.Roles)
            if err != nil {
                return err
            }
    
            err = db.Delete(&clientToRemove).Error
            if err != nil {
                return err
            }
    
            return nil
        })

我希望删除角色中的相关行,而不是删除查询,而是执行更新查询以删除 client_id。

[210.834ms] [rows:1] UPDATE "role" SET "client_id"=NULL WHERE "role"."client_id" = 'xxxxxxxxxxx' AND "role"."id" = 9

如何完全删除关联角色表中的行?

数据库是 Postgres

【问题讨论】:

  • 您可以使用 ON DELETE CASCADE 作为数据库架构中的外键,然后删除客户端。

标签: postgresql windows go go-gorm


【解决方案1】:

documentation 中所述,删除关联操作只会删除ClientTenantRole 之间的引用。在您的情况下,它只是更新了TenantRole 记录以将client_id 设置为NULL。

如果您还想删除对象,可以尝试使用Select 进行删除操作。请note 这仅在主键不为零时才有效,因此您的查询可能如下所示:

err = db.Select("TenantRoles").Delete(&Client{Id: clientId}).Error

或者只使用 clientToRemove 如果它已经填充了 Id 字段

err = db.Select("TenantRoles").Delete(&clientToRemove).Error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-29
    • 2010-11-04
    • 2015-12-02
    • 1970-01-01
    • 2012-02-13
    • 2021-10-03
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多