Reputation: 51
Help me. I'm stuck at this, I make a checkRecordExistence to check for the existence of a record.This function take a model as an interface type, i pass the model down to the First function which also take model as an interface type but it doesnt work
func checkRecordExistence(model interface{}, query string, field ...interface{}) bool {
if err := db.GetDB().Where(query, field...).First(model).Error; gorm.IsRecordNotFoundError(err) {
return false
}
return true
}
// GetPlaylists of a specific user
func GetPlaylists(username string) (playlists []Playlist) {
playlists = []Playlist{}
user := User{}
if exist := checkRecordExistence(user, "username = ?", username); !exist {
return
}
db.GetDB().Preload("Songs.Artists").Preload("Songs").Model(&user).Related(&playlists, "UserRefer")
return
}
When i call the GetPlaylists function it crashed
eflect.Value.Addr of unaddressable value
/usr/lib/go/src/runtime/panic.go:513 (0x42c4d8)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/usr/lib/go/src/reflect/value.go:245 (0x4ae0c5)
Value.Addr: panic("reflect.Value.Addr of unaddressable value")
/home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/callback_query.go:74 (0x54f1b4)
queryCallback: scope.scan(rows, columns, scope.New(elem.Addr().Interface()).Fields())
/home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/scope.go:857 (0x5767a4)
(*Scope).callCallbacks: (*f)(scope)
/home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/main.go:289 (0x56528e)
(*DB).First: inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
/home/anhthi/go/src/github.com/anhthii/go-echo/db/models/playlist.go:35 (0x676c06)
checkRecordExistence: if err := db.GetDB().Where(query, field...).First(model).Error; gorm.IsRecordNotFoundError(err) {
/home/anhthi/go/src/github.com/anhthii/go-echo/db/models/playlist.go:45 (0x676dfc)
GetPlaylists: if exist := checkRecordExistence(user, "username = ?", username); !exist {
I think the problem is here: .Where(query, field...).First(model) but i can't find any solution, thanks if anyone can help me.
Upvotes: 1
Views: 271
Reputation: 632
According to https://github.com/jinzhu/gorm/issues/394, parameter model
should be a pointer. I think the code below would work.
if exist := checkRecordExistence(&user, "username = ?", username); !exist {
return
}
Upvotes: 3