Batch inserting in gorm with has-many association

Viewed 63

This is my model:

type Identity struct {
    gorm.Model
    Name         string
    Results      []Result
}

type Result struct {
    gorm.Model
    IdentityID        uint
    Identity          Identity                `gorm:"foreignkey:IdentityID"`
    Link              string
}

I intend Identity to have a has-many relationship with Result. The Identity may or may not already exist with some []Result. I am trying to perform a bulk insert, while creating/appending any results to a new or existing identity:

results := []models.Result{
    {
        Identity: models.Identity{
            Name: "one",
        },
        Link: "https://example.com",
    },
}

if err := r.DB.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(results, 2000).Error; err != nil {
    return nil, err
}

I get this error when trying:

pq: insert or update on table "results" violates foreign key constraint "fk_identities_results"

Is there something wrong with my data model, or how I am trying to insert?

0 Answers
Related