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