admin管理员组文章数量:1397839
I have a slice of structs, that contain their id (each id is valid). I want to find all the data from the database corresponding to those ids.
Example of something I would want (this does not work):
func RetrieveProfiles(db *gorm.DB, profiles []Profile) ([]Profile, error) {
var result []Profile
// Find profiles using the existing id in each item from profiles slice
err := db.Model(Profile{}).Where("id IN ?", profiles).Find(&result)
return result, err
}
I've tried multiple variations, and I either got empty slices or errors.
I want this since I'm displaying these profiles in an UI, and want to update their data, so it would be convenient to just give the input of already existing profiles and switch the slice in place with the updated profiles. But I would want to avoid looping through the slice again to just extract the ids, and plug that into the query.
Is this possible without looping through the input slice and extracting the ids?
func RetrieveProfiles(db *gorm.DB, profiles []Profile) ([]Profile, error) {
var result []Profile
// Avoid this
ids := make([]string, len(profiles))
for index, profile := range profiles {
ids[index] = profile.Id
}
// Find profiles using the existing id in each item from profiles slice
err := db.Model(Profile{}).Where("id IN ?", ids).Find(&result)
return result, err
}
本文标签: sqlgorm Is it possible to use slice of structs as input in queryStack Overflow
版权声明:本文标题:sql - gorm: Is it possible to use slice of structs as input in query? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744160213a2593302.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论