Golang SQLBoiler 动态追加查询

huangapple go评论84阅读模式
英文:

Golang SQLBoiler append queries dynamically

问题

我正在尝试动态运行对我的Postgres数据库的查询,但我无法完全理解它。

我正在寻找的解决方案是可以动态设置查询,可能通过在代码中向最终查询追加参数,然后只执行一个查询实例。

如标题所述,我正在使用SQLBoiler与Postgres进行接口交互。

以下是我在伪代码中寻找的内容:

final_query := QueryMod{
    Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
}

if a == 1 {
    final_query = append(final_query, And(" and mt_important = ?", bool(false)))
} else {
    final_query = append(final_query, And(" and mt_ness = ?", bool(true)))
}

res_mt_count, err := models.MTs(
    final_query,
).All(CTX, DB)

感谢您的帮助! Golang SQLBoiler 动态追加查询

英文:

I'm trying to dynamically run queries against my Postgres database, but can't fully wrap my head around it.

The solution I'm looking for is one where I can set the query dynamically, perhaps by appending parameters to the final query throughout the code, and then have only one instance of the query being executed.

As mentioned in the title I am using SQLBoiler to interface with Postgres.

Here's what I'm looking for in pseudo code:

final_query := QueryMod{
    Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
}

if a == 1 {
    final_query = append(final_query, And(" and mt_important = ?", bool(false)))
} else {
    final_query = append(final_query, And(" and mt_ness = ?", bool(true)))
}

res_mt_count, err := models.MTs(
    final_query,
).All(CTX, DB)

Thankful for any help along the way! Golang SQLBoiler 动态追加查询

答案1

得分: 3

mkopriva用以下解决方案解决了我的问题:

type QueryModSlice []qm.QueryMod

func (s QueryModSlice) Apply(q *queries.Query) {
	qm.Apply(q, s...)
}

func main() {
	mods := QueryModSlice{
		qm.Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
	}

	if a == 1 {
		mods = append(mods, qm.And(" and mt_important = ?", bool(false)))
	} else {
		mods = append(mods, qm.And(" and mt_ness = ?", bool(true)))
	}

	res_mt, err := models.MTs(mods).All(CTX, DB)

}

非常感谢! Golang SQLBoiler 动态追加查询

英文:

mkopriva solved my problems with the following solution:

type QueryModSlice []qm.QueryMod

func (s QueryModSlice) Apply(q *queries.Query) {
	qm.Apply(q, s...)
}

func main() {
	mods := QueryModSlice{
		qm.Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
	}

	if a == 1 {
		mods = append(mods, qm.And(" and mt_important = ?", bool(false)))
	} else {
		mods = append(mods, qm.And(" and mt_ness = ?", bool(true)))
	}

	res_mt, err := models.MTs(mods).All(CTX, DB)

}

Thanks a bunch! Golang SQLBoiler 动态追加查询

huangapple
  • 本文由 发表于 2021年8月11日 02:18:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/68731784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定