R P
R P

Reputation: 43

Gorm "Insert Ignore"

I am trying to implement "Insert Ignore" in GORM. I tried Create() but I couldn't find a way to add Ignore. I also tried Clause in Gorm,

DB.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(&user)`.

However, I got an error says Clauses undefined (type *"github.com/jinzhu/gorm".DB has no field or method Clauses).

I also tried to use DB.Raw(), but I don't know how to change the table each time since I have so many tables in my database. For example

DB.Raw("INSERT IGNORE INTO A/B/C/.. ... ...")`. 

I have a lot of tables that will go through this function, each time I might insert into a different table.

I am wondering if anybody has experience with Insert Ignore in GORM. Thanks!

Upvotes: 4

Views: 8600

Answers (2)

NineRec
NineRec

Reputation: 11

For Gorm v2 the answer is clear: Clause in Gorm.

For Gorm v1, you can find the solution in Gorm v1's tests. refer: https://github.com/jinzhu/gorm/blob/master/create_test.go#L285

    if DB.Dialect().GetName() == "mysql" && DB.Set("gorm:insert_modifier", "IGNORE").Create(&user).Error != nil {
        t.Error("Should ignore duplicate user insert by insert modifier:IGNORE ")
    }

I met the issue several times as lots of our team still have lots of code using Gorm v1...

Upvotes: 0

ttrasn
ttrasn

Reputation: 4851

Hi and welcome to StackOverflow.

I think you are using gorm v1. but the code you need is on gorm v2.

first, you must get Gorm v2 and MySQL dialector by run this commands on your terminal.

go get -u gorm.io/gorm // get gorm v2
go get -u gorm.io/driver/mysql // get dialector of mysql from gorm

then you can use Clauses of gorm.

this code will be work for you.

import (
   "gorm.io/gorm"
   "gorm.io/driver/mysql"
)


func main(){
    db, err := gorm.Open(mysql.Open(MYSQL_CONNECTION_STRING), &gorm.Config{})

    if err != nil {
        fmt.Println(err.Error())
    }else{
        db.Clauses(clause.Insert{Modifier: "IGNORE"}).Create(&user)
    }
}

Upvotes: 1

Related Questions