jwthanh
jwthanh

Reputation: 73

Build custom query with gorm Golang lib

I'm using http://jinzhu.me/gorm/crud.html#query

I want to build selectQuery base on some custom conditions

selectQuery := db.Select("username").Where("status = 'active'")
selectQuery.Limit(10)
if err := selectQuery.Find(&users).Error; err != nil {
//
} else {
//
}

Why limit is not applied?

It’s working if implemented with below code:

if err := db.Select("username").Where("status = 'active").Limit(10).Find(&users).Error; err != nil {
//
} else {
//
}

Upvotes: 1

Views: 1101

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79536

Why limit is not applied?

Because you're ignoring the return value of Limit. In effect, you're creating a query with a limit, then throwing it away without ever executing it.

You need to use:

selectQuery = selectQuery.Limit(10)

Upvotes: 1

Related Questions