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

能否新增WhereIf 根据值过滤条件 #7277

Closed
yibird opened this issue Nov 12, 2024 · 3 comments
Closed

能否新增WhereIf 根据值过滤条件 #7277

yibird opened this issue Nov 12, 2024 · 3 comments
Assignees
Labels

Comments

@yibird
Copy link

yibird commented Nov 12, 2024

原来是这样的:

db := s.DB.Model(&Role{})
	if query.Code != "" {
		db = db.Where("code like ?", "%"+query.Code)
	}
	if query.Name != "" {
		db = db.Or("name like ?", "%"+query.Name)
	}

现在新增了WhereIf:

// WhereIf 在条件满足时添加 Where 条件
func WhereIf(db *gorm.DB, query string, value interface{}) *gorm.DB {
	switch value.(type) {
	case int:
		if value != 0 {
			return db.Where(query, value)
		}
	case string:
		if value != "" && value != nil {
			return db.Where(query, value)
		}
	case bool:
		if value != false {
			return db.Where(query, value)
		}
	}
	return db
}

由于*gorm.DB是内部类型,因此无法实现链式调用,希望gorm能内置WhereIf和OrIf

@github-actions github-actions bot added the type:missing reproduction steps missing reproduction steps label Nov 12, 2024
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

@jinzhu
Copy link
Member

jinzhu commented Nov 15, 2024

You can implement similar logic based on Scopes.

@jinzhu jinzhu closed this as completed Nov 15, 2024
@yibird
Copy link
Author

yibird commented Dec 24, 2024

You can implement similar logic based on Scopes.您可以基于作用域实现类似的逻辑。

您好,虽然自定义也可以实现,但是需要用户手动编写,而且很多人需要这个功能,因此我觉得作为框架内置api是一个好的选择

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants