简体   繁体   English

是否可以将多个 Select 子句与 gorm 链接起来?

[英]Is it possible to chain several Select clauses with gorm?

I know I can chain several Where clauses using gorm, but can I do the same with several Select clauses?我知道我可以使用 gorm 链接几个 Where 子句,但是我可以对几个 Select 子句做同样的事情吗?

I've tried something like this with no luck:我试过这样的事情没有运气:

query.Select("field1, field2").Select("field3").Find(&models)

The fact is that I need to chain different select clauses depending on certain conditions.事实是,我需要根据某些条件链接不同的 select 子句。 How to achieve this?如何做到这一点?

Chaining multiple Select() calls won't work, as it will only apply the last one.链接多个Select()调用将不起作用,因为它只会应用最后一个调用。 So in your example, the query will look like:因此,在您的示例中,查询将如下所示:

SELECT "field3" FROM "model";

Select() also accepts a []string , so instead, make a slice of strings representing the fields that you need to SELECT , and append to it other columns under certain conditions: Select()也接受[]string ,因此,在某些条件下,将一段字符串表示您需要SELECT和 append 到其他列的字段:

selects := []string{"field1", "field2"}

if condition {
    selects = append(selects, "field3")
}

query.Select(selects).Find(&models)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM