Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on insert or update on table violates foreign key constraint #5629

Open
Robbie-Perry opened this issue Aug 19, 2022 · 1 comment
Open
Assignees
Labels

Comments

@Robbie-Perry
Copy link

Your Question

I have the following set of GORM models, with 2 orders of one-to-many relations:

type Order struct {
	ID       string  `gorm:"column:id"`
	ClientID string  `gorm:"primaryKey;column:client_id"`
	Name     string  `gorm:"column:name"`
	Albums   []Album `gorm:"foreignKey:RequestClientID"`
}

type Album struct {
	AlbumID         string    `gorm:"primaryKey;column:album_id"`
	RequestClientID string    `gorm:"foreignKey:ClientID;column:request_client_id"`
	Pictures        []Picture `gorm:"foreignKey:AlbumID"`
}

type Picture struct {
	PictureID   string `gorm:"primaryKey;column:picture_id"`
	AlbumID     string `gorm:"foreignKey:AlbumID;column:album_id"`
	Description string `gorm:"column:description"`
}

When I attempt to insert data as follows, I get the error pq: insert or update on table "albums" violates foreign key constraint "fk_orders_albums".

test := Order{
	ID:       "abc",
	ClientID: "client1",
	Name:     "Roy",
	Albums: []Album{
		{
			AlbumID: "al_1",
			Pictures: []Picture{
				{
					PictureID:   "pic_1",
					Description: "test pic",
				},
			},
		},
	},
}

gormDB.Save(&test)

The document you expected this should be explained

I followed the steps in the Has Many page of the docs, to no avail.

Expected answer

What might I be doing wrong here? Thank you!

@Robbie-Perry Robbie-Perry added the type:question general questions label Aug 19, 2022
@github-actions
Copy link

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants