I am new to Go and my pointer knowledge is rusty. I want to mutate an instance of the gorm.DB so that I can apply 0 or more Where
clauses to it.
func () {
db := gorm.Open(/* ... */)
err := applyWhere(db, filters).Order("created_datetime desc").Find(&rMessages).Error
// ...
}
func applyWhere(db *gorm.DB, filters Filters) *gorm.DB {
if filters.MessageType != "" {
db = db.Where(&message{MessageType: string(filters.MessageType)})
}
return db
}
This seems not to work. The db instance doesn't have the where applied.
* edit 3 *
This now works. Not sure what the problem was before. Please close / delete this question.
Read on how to do chaining with GORM properly here: Method Chaining tutorial. You take the *gorm.DB
returned by one method and apply another method to it, that's it. You can also pass the *gorm.DB
around, but be careful to only pass the pointer, not dereference it (otherwise you get the lock copy error as you found).
Order
s are just another kind of query you can chain: http://gorm.io/docs/query.html#Order
For example:
var p Product
db.Order("Price").Where("Price > 1000").First(&p)
So your applyWhere
should just return *gorm.DB
which you can further query