set_primary_keys.go 707 B

12345678910111213141516171819202122232425262728293031323334
  1. package utils
  2. import (
  3. "github.com/sunfmin/reflectutils"
  4. "gorm.io/gorm"
  5. )
  6. func SetPrimaryKeys(from, to interface{}, db *gorm.DB, paramId string) (err error) {
  7. stmt := &gorm.Statement{DB: db}
  8. if err = stmt.Parse(to); err != nil {
  9. return
  10. }
  11. for _, v := range stmt.Schema.PrimaryFields {
  12. if v.Name == "Version" {
  13. if _, err = to.(interface {
  14. CreateVersion(db *gorm.DB, paramID string, obj interface{}) (string, error)
  15. }).CreateVersion(db, paramId, to); err != nil {
  16. return
  17. }
  18. continue
  19. }
  20. var value interface{}
  21. value, err = reflectutils.Get(from, v.Name)
  22. if err != nil {
  23. return
  24. }
  25. err = reflectutils.Set(to, v.Name, value)
  26. if err != nil {
  27. return
  28. }
  29. }
  30. return
  31. }