简体   繁体   English

如何防止子模型在 Golang GORM 中被删除?

[英]How to prevent Child models from Deletion in Golang GORM?

Well, I would like to know, Is there any solutions, how to prevent Child Model from deletion in foreignKey Constraint, (好吧,我想知道,有什么解决办法,如何防止Child Model在foreignKey Constraint中被删除,(

For example in gorm there is a couple of options that allows to restrict behavior of the Parent Model after deletion, and Delete or Set to Null the Child Model Objects That has foreignKey relation (onDelete: Cascade / Set Null, and the same thing for onUpdate) For example in gorm there is a couple of options that allows to restrict behavior of the Parent Model after deletion, and Delete or Set to Null the Child Model Objects That has foreignKey relation (onDelete: Cascade / Set Null, and the same thing for onUpdate )

// Pretty a lot of the same words, but I hope you got it:) // 有很多相同的词,但我希望你明白了:)

Little Example.. from Golang...小例子......来自Golang......


type SomeOtherStruct struct {
     gorm.Model
     Id int 

} 

type SomeModel struct {
    gorm.Model
    someOtherStructId string 

    someField SomeOtherStruct `gorm:"foreignKey:SomeOtherStructId; OnDelete:Cascade,OnUpdate: SET NULL"` // basically foreign Key Relationship to model `SomeOtherStruct`
}

But I would like to prevent any Update/Deletion behavior, so Child Relation Models Objects won't get deleted after the Parent Model Object has been..但我想防止任何更新/删除行为,因此在父 Model Object 之后,不会删除子关系模型对象。

There is actually a concept from Django Framework (Python)实际上有一个来自 Django 框架(Python)的概念

class SomeModel(models.Model):
     
    some_field = models.ForeignKey(to=AnotherModel,   verbose_name="SomeField", on_delete=models.PROTECT) 

class AnotherModel(models.Model):
     pass 

As you can see, there is models.PROTECT constraint, that is basically what I'm looking for....如您所见,有models.PROTECT约束,这基本上就是我正在寻找的......

Is there any analogy for that in Golang GORM or some RAW SQL for that as well?在 Golang GORM 或一些RAW SQL中是否有任何类比?

Thanks..谢谢..

Unfortunately, you didn't mention which database you are using.不幸的是,您没有提及您使用的是哪个数据库。

In Postgres (as an example) there are multiple options for ON DELETE :在 Postgres(例如)中有多个ON DELETE选项:

  • NO ACTION
  • RESTRICT
  • CASCADE
  • SET NULL
  • SET DEFAULT

Only CASCADE will delete children if the parent is deleted.如果父级被删除,只有CASCADE会删除子级。 All other options (including the default NO ACTION ) will make sure the children will "survive".所有其他选项(包括默认的NO ACTION )将确保孩子们“生存”。

You can find more information in the postgres documentation: https://www.postgresql.org/docs/current/sql-createtable.html您可以在 postgres 文档中找到更多信息: https://www.postgresql.org/docs/current/sql-createtable.html

Please feel free to update your question and/or comment with the database you are using.请随时使用您正在使用的数据库更新您的问题和/或评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM