简体   繁体   中英

Querying for multiple columns with Gorm

My db includes the following columns, "model_package" and "model_variant". I try to query the db with Gorm by specifying both of these columns inside.Select(), however, I keep getting a scan error. Normally, when I select a single column (ie .Select("model_package") ), it returns to an array(slice) containing all the values, so I assumed it should return to a two-dimension array(slice) when I select multiple columns like in my code below.

My goal is to combine both fields into a string. For example, if a row in db has the following values "model_package": "pkg1" and "model_variant": "var1", then I want to create this string "pkg1_var1". How can I construct the correct query to get both values for each row on the db.

My code:

func (s *store) ListAllModelNames() ([][]string, error) {
    var modelNames [][]string
    result := s.db.Table(mfcTable).Select("model_package", "model_variant").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}

Error:

sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer

A couple of options you can try out:

Option 1 - create a view model for your SELECT query and return that to do with it what you want.

type ModelName struct {
   ModelPackage string
   ModelVariant string
}

func (s *store) ListAllModelNames() ([]ModelName, error) {
    var modelNames []ModelName
    result := s.db.Table(mfcTable).Select("model_package", "model_variant").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}

Option 2 - do the concatenation with the CONCAT() function within your SELECT query.

func (s *store) ListAllModelNames() ([]string, error) {
    var modelNames []string
    result := s.db.Table(mfcTable).Select("CONCAT(model_package, "_", model_variant)").Where("model_package IS NOT NULL AND model_variant IS NOT NULL").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM