I have the following struct
type Category struct {
gorm.Model
Name string `gorm:"type:varchar(128);not null;unique"`
}
which is associated to Item
struct
:
// Item is a type representing a job listing on stackoverflow jobs
type Item struct {
GUID string `gorm:"primary_key"`
Link string
Categories []Category `gorm:"many2many:item_categories"`
}
I'd like to save Item
s in db using gorm together with associations in table item_categories
The problem arises when I INSERT
an Item
which has at least on Category
that is already in the DB (because of the UNIQUE
constraint on Category.Name
) then I get an error while doing:
var item Item
// fill item...
db.Create(&item)
and it propagates so that all INSERT
s (of Item
, Category
and Item_Categories
) are not performed.
I've tried using BeforeCreate
/AfterCreate
but the result is the same
func (c *Category) BeforeCreate(scope *gorm.Scope) (err error) {
if err = scope.DB().Where(&Category{Name: c.Name}).First(c).Error; err == nil {
return fmt.Errorf("Category %s already found in DB", c.Name)
}
return nil
}
What can I do to make it insert Item
s (and related new categories) with categories that are already in the DB?
Example of log I receive when adding a category (inside an Item
) that already exists in the DB:
(/home/USER/.gvm/pkgsets/go1.9.4/global/src/github.com/USER/project/model.go:33)
[2018-02-19 13:42:46] [0.17ms] SELECT * FROM "categories" WHERE "categories"."deleted_at" IS NULL AND (("categories"."name" = 'go')) ORDER BY "categories"."id" ASC LIMIT 1
[1 rows affected or returned ]
BeforeCreate First
Category &{{4 2018-02-19 13:42:46.164188984 +0100 +0100 2018-02-19 13:42:46.164188984 +0100 +0100 <nil>} go}
(/home/USER/.gvm/pkgsets/go1.9.4/global/src/github.com/USER/project/storage.go:20)
[2018-02-19 13:42:46] Category go already found in DB
(/home/USER/.gvm/pkgsets/go1.9.4/global/src/github.com/USER/project/storage.go:20)
[2018-02-19 13:42:46] Category go already found in DB
(<autogenerated>:1)
[2018-02-19 13:42:46] [0.12ms] INSERT INTO "item_categories" ("item_guid","category_id") SELECT '157652','4' WHERE NOT EXISTS (SELECT * FROM "item_categories" WHERE "item_guid" = '157652' AND "category_id" = '4')
[1 rows affected or returned ]
(/home/USER/.gvm/pkgsets/go1.9.4/global/src/github.com/USER/project/storage.go:20)
[2018-02-19 13:42:46] Category go already found in DB
(/home/USER/.gvm/pkgsets/go1.9.4/global/src/github.com/USER/project/storage.go:20)
[2018-02-19 13:42:46] Category go already found in DB
2018/02/19 13:42:46 Couldn't save job listing 157652 in db: Category go already found in DB