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

How to create a new column as a foreign key? #1123

Open
grandwizard28 opened this issue Feb 11, 2025 · 1 comment
Open

How to create a new column as a foreign key? #1123

grandwizard28 opened this issue Feb 11, 2025 · 1 comment

Comments

@grandwizard28
Copy link

I'm using bun migrations and have already run a migration like the following:

if _, err := db.NewCreateTable().
		Model(&struct {
			bun.BaseModel `bun:"table:<redacted>"`
			ID            int       `bun:"id,pk,autoincrement"`
			CreatedAt     time.Time `bun:"created_at,type:datetime,notnull"`
			UpdatedAt     time.Time `bun:"updated_at,type:datetime,notnull"`
		}{}).
		IfNotExists().
		Exec(ctx); err != nil {
		return err
	}

The migration has ran successfully and the migration table has already recorded that this group is complete. I now want to add a new column to the above table and add a foreign key constraint to it. I tried the following:

	if _, err := db.
		NewAddColumn().
		Table("<redacted>").
		ColumnExpr("org_id TEXT").
		Exec(ctx); err != nil {
		return err
	}

But this just adds an org_id. How do I create a foreign key constraint out of it?

@j2gg0s
Copy link
Collaborator

j2gg0s commented Feb 12, 2025

I'm sorry that you should use raw sql by db.RawQuery

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

No branches or pull requests

2 participants