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 use a model with self-reference ? #531

Open
rodrigoodhin opened this issue May 12, 2022 · 2 comments
Open

How to use a model with self-reference ? #531

rodrigoodhin opened this issue May 12, 2022 · 2 comments
Labels

Comments

@rodrigoodhin
Copy link

Hello everyone!

I've created a model with self-reference field but it's not working as expected.

My model:

type Category struct {
	db.Model
	Name        string    `json:"name" bun:",notnull,unique"`
	Description string    `json:"description"`
	Slug        string    `json:"slug" bun:",notnull"`
	RootID      uuid.UUID `json:"root_id" bun:",type:uuid,nullzero"`
	Root        *Category `json:"root" bun:",nullzero,rel:belongs-to,join:root_id=id"`
}

My Migration:

db.NewCreateTable().
		Model(&Category{}).
		IfNotExists().
		WithForeignKeys().
		ForeignKey(`(root_id) REFERENCES categories (id) ON UPDATE CASCADE ON DELETE SET NULL`).
		Exec(ctx)

My list query:

var categories []Category
db.NewSelect().Model(&Category{}).Scan(ctx, &categories)

How to return "Root" info in this query?
How to upsert this model to insert Category and Root?

Thank!

@l0nax
Copy link
Contributor

l0nax commented Feb 28, 2023

You have two possibilities:

Copy link

github-actions bot commented Nov 7, 2024

This issue has been automatically marked as stale because it has not had activity in the last 30 days. If there is no update within the next 7 days, this issue will be closed.

@github-actions github-actions bot added the stale label Nov 7, 2024
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