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

给自定义SQL增加了根据条件判断是否生成的功能 #191

Merged
merged 3 commits into from
Jan 7, 2022
Merged

给自定义SQL增加了根据条件判断是否生成的功能 #191

merged 3 commits into from
Jan 7, 2022

Conversation

jiang4869
Copy link
Collaborator

@jiang4869 jiang4869 commented Jan 6, 2022

给自定义SQL增加了根据条件判断是否生成的功能。因为有时候在查询时,某些字段需要根据前端传过来的查询参数来决定是否需要,例如对文章标题或者内容字段进行查找时,只有当前端传递过来的title这个字段不为空时才需要添加。使用类似下列情况

query := model.Query{}
query.AndOnCondition(vo.GetTitle()!= nil,"title","=",vo.GetTitle())
query.And("username", "=", "name1")

像下面这个生成的sql为

query := model.Query{}
query.And("username", "=", "name1")
query.OrOnCondition(false, "password", "=", "pwd1")
fmt.Println(query.Get())
`username` = ? [name1]

在使用自定义SQL时,直接把Get()的返回值当作参数传给db.Where() 会出现下列问题,所有的参数都只会被放到第一个变量里面而已。

SELECT * FROM `blog_admin` WHERE `username` = ('name1','pwd1') or `password` = ?

所以应该接受Get()的返回值后,再分别传入

accountMgr := model.AccountMgr(db.Where(where, obj))

@xxjwxc
Copy link
Owner

xxjwxc commented Jan 6, 2022

你用condition条件试下把obj改成obj...

@xxjwxc
Copy link
Owner

xxjwxc commented Jan 6, 2022

正确做法应该像这种:
accountMgr := model.AccountMgr(db.Where(where, obj...))

@jiang4869
Copy link
Collaborator Author

正确做法应该像这种: accountMgr := model.AccountMgr(db.Where(where, obj...))

对,忘记把...给加上去了。

原本那个使用示例里面是这么写的,所以我给改了

accountMgr := model.AccountMgr(db.Where(condition.Get()))

@xxjwxc
Copy link
Owner

xxjwxc commented Jan 7, 2022

这个我觉得不太有必要:
可以这样来:
query := model.Query{}
if vo.GetTitle()!= nil {
query.And("title","=",vo.GetTitle())
}
query.And("username", "=", "name1")

正在考虑支持这个:
#166

@jiang4869
Copy link
Collaborator Author

这个我觉得不太有必要: 可以这样来: query := model.Query{} if vo.GetTitle()!= nil { query.And("title","=",vo.GetTitle()) } query.And("username", "=", "name1")

正在考虑支持这个: #166

之前也考虑过这种写法,不过这么写会让代码冗余很多,也不方便进行链式调用,所以才加了这么个功能。

@xxjwxc
Copy link
Owner

xxjwxc commented Jan 7, 2022

可以修改下:model.Query 还是用condition来吧。类改掉之后增量升级会有问题

@xxjwxc xxjwxc merged commit 9e62d21 into xxjwxc:master Jan 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants