Skip to content

Instantly share code, notes, and snippets.

@hauxe
Created June 3, 2018 06:27
Show Gist options
  • Save hauxe/476266d32b4b76ae32578852605d07f5 to your computer and use it in GitHub Desktop.
Save hauxe/476266d32b4b76ae32578852605d07f5 to your computer and use it in GitHub Desktop.
crud create function
// Create creates from map
func (crud *CRUD) Create(data interface{}) error {
// build fields
result, err := crud.Config.DB.NamedExec(crud.Config.sqlCRUDCreate, data)
if err != nil {
return errors.Wrap(err, "error crud create")
}
// set primary key
rv := reflect.ValueOf(data)
rv = reflect.Indirect(rv)
pk := rv.Field(crud.Config.pk.index)
if pk.CanSet() && pk.Kind() == reflect.Int64 {
id, err := result.LastInsertId()
if err != nil {
return errors.Wrap(err, "error get last insert id at crud create")
}
pk.SetInt(id)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment