Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何全局禁用掉关联表数据的默认写和删除操作 #7341

Open
molon opened this issue Jan 9, 2025 · 1 comment
Open

如何全局禁用掉关联表数据的默认写和删除操作 #7341

molon opened this issue Jan 9, 2025 · 1 comment
Assignees
Labels
type:question general questions

Comments

@molon
Copy link
Contributor

molon commented Jan 9, 2025

Your Question

在我目前的项目里,会需要使用 Preload Joins 这样的方法,但是确实不需要写操作的时候也去处理关联数据,所以我期望能全局禁用掉这个默认或者非默认行为,防止团队成员使用导致非预期错误。

经过调研,找到了三种方式,但是各有利弊,希望能得到指点。

目前是倾向于 移除相关的 callbacks 会比较彻底和方便,但是我对此有些担心直接 remove 掉是否会有其他隐患。
希望这点上能得到解答。🙏

https://github.com/molon/tests/blob/ee9470efe9de680a26038053c7ff7bcf88693af9/gorm/ass_test.go#L403-L491

Update

找到另外一种感觉更可靠的方式如下

omitAssociations := func(db *gorm.DB) {
	db.Statement.Omit(clause.Associations)
}
db.Callback().Create().Before("gorm:save_before_associations").Register("omit_associations", omitAssociations)
db.Callback().Delete().Before("gorm:delete_before_associations").Register("omit_associations", omitAssociations)
db.Callback().Update().Before("gorm:save_before_associations").Register("omit_associations", omitAssociations)

想知道此种方式是否 OK 且没有其他隐患。

The document you expected this should be explained

Expected answer

@molon molon added the type:question general questions label Jan 9, 2025
@github-actions github-actions bot added type:missing reproduction steps missing reproduction steps and removed type:question general questions labels Jan 10, 2025
Copy link

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.ioSearch Before Asking

@github-actions github-actions bot added status:stale type:question general questions and removed type:missing reproduction steps missing reproduction steps status:stale labels Jan 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants