【问题标题】:How to avoid duplicate row while gorm AutoMigrategorm AutoMigrate时如何避免重复行
【发布时间】:2021-11-17 15:37:16
【问题描述】:

我想使用 gorm AutoMigrate 从 CSV 文件插入数据库,并且在插入时我想避免重复输入。我怎样才能做到这一点?请检查随附的代码。

type User struct {
    gorm.Model

    ID                           int64  `csv:"_" db:"id"`
    FirstName                    string `csv:"First name" db:"first_name"`
    LastName                     string `csv:"Last name" db:"last_name"`
    Emails                       string `csv:"Emails" db:"emails"`
}

func main() {
    file, err := os.Open(os.Args[1])
    defer file.Close()
    users := []User{}
    err = gocsv.Unmarshal(file, &users)
    db, err := gorm.Open(postgres.Open("host=xxx.xx.x.x user=database password=password dbname=database port=5432 sslmode=disable"))

    err = db.AutoMigrate(&User{})
    if err != nil {
        panic(err)
    }

    result := db.Create(users)
    if result.Error != nil {
        panic(result.Error)
    }
}

示例:考虑以下数据

FIrst name Last name Emails
First Name first@example.com
Second Name second@example.com
Third Name
Forth Name first@example.com

如果我们传递上述数据,前 3 行应该插入到数据库中,即我们必须避免重复的电子邮件条目到数据库中。谢谢。

注意:如果电子邮件为空,则应将该行插入数据库。

【问题讨论】:

    标签: postgresql go go-gorm golang-migrate


    【解决方案1】:

    你必须在err = gocsv.Unmarshal(file, &users)之后清理“用户”

    有点像

    func sanytize(arr []User) []User {
       users := []User{}
       mail := []string{}
       for _, a := range arr {
           if !contains(mail, a.Emails){
               users = append(users, a)
           }
           mail = append(mail, a.Emails)
           
       }
       
       return users
    }
    
    func contains(arr []string, str string) bool {
       for _, a := range arr {
          if a == str {
             return true
          }
       }
       return false
    }
    
    ....
    
    err = gocsv.Unmarshal(file, &users)
    users = sanytize(users)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2015-09-12
      相关资源
      最近更新 更多