英文:
How to prevent Child models from Deletion in Golang GORM?
问题
嗯,我明白你的问题。你想知道如何在外键约束中防止删除子模型的解决方案。在gorm中,有一些选项可以限制父模型在删除后的行为,并删除或将子模型对象设置为Null,这些选项包括onDelete: Cascade / Set Null和onUpdate: Cascade / Set Null。
以下是一个来自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"`
}
但是你想要防止任何更新/删除行为,以便在父模型对象被删除后,子关联模型对象不会被删除。在Django框架(Python)中,有一个名为models.PROTECT
的约束,它可以实现这个功能。
class SomeModel(models.Model):
some_field = models.ForeignKey(to=AnotherModel, verbose_name="SomeField", on_delete=models.PROTECT)
class AnotherModel(models.Model):
pass
你想知道在Golang的GORM中是否有类似的概念或者是否有一些原始的SQL语句可以实现这个功能。
英文:
Well, I would like to know, Is there any solutions, how to prevent Child Model from deletion in 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)
// Pretty a lot of the same words, but I hope you got it
Little Example.. from 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..
There is actually a concept from Django Framework (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....
Is there any analogy for that in Golang GORM or some RAW SQL
for that as well?
Thanks..
答案1
得分: 0
很抱歉,你没有提到你使用的是哪个数据库。
在Postgres中(以此为例),有多个ON DELETE
选项:
NO ACTION
RESTRICT
CASCADE
SET NULL
SET DEFAULT
只有CASCADE
选项会在删除父项时同时删除子项。其他所有选项(包括默认的NO ACTION
)都会确保子项“存活”。
你可以在Postgres文档中找到更多信息:https://www.postgresql.org/docs/current/sql-createtable.html
请随时更新你的问题和/或评论,告诉我你使用的数据库。
英文:
Unfortunately, you didn't mention which database you are using.
In Postgres (as an example) there are multiple options for ON DELETE
:
NO ACTION
RESTRICT
CASCADE
SET NULL
SET DEFAULT
Only CASCADE
will delete children if the parent is deleted. All other options (including the default NO ACTION
) will make sure the children will "survive".
You can find more information in the postgres documentation: 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论