如何防止gorm在违反UNIQUE约束时无法保存关联?

时间:2018-02-19 13:04:12

标签: go go-gorm

我有以下struct

type Category struct {
  gorm.Model
  Name string `gorm:"type:varchar(128);not null;unique"`
}

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"`
}

我想使用gorm以及表Item

中的关联将item_categories保存在数据库中

问题出现在INSERT Item {至少Category已存在于数据库中{由于UNIQUE约束Category.Name })然后我在做的时候出错:

var item Item
// fill item...
db.Create(&item)

并传播,以便不执行INSERTItemCategory的所有Item_Categories个。

我已尝试使用BeforeCreate / AfterCreate但效果相同

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
}

如何将Item s(以及相关的类别)与数据库中已有的类别一起插入?

添加DB中已存在的类别(Item内)时收到的日志示例:

(/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

0 个答案:

没有答案