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

Custom sum column on a relation #980

Open
thecampagnards opened this issue Apr 22, 2024 · 0 comments
Open

Custom sum column on a relation #980

thecampagnards opened this issue Apr 22, 2024 · 0 comments

Comments

@thecampagnards
Copy link

thecampagnards commented Apr 22, 2024

Hello,

I have an issue doing a custom sum column on a relation, here an example:

type A struct {
	bun.BaseModel `bun:"table:a,alias:a"`
	ID            uint `bun:"id,pk,autoincrement"`
	Bs            []B  `bun:"rel:has-many,join:id=a_id"`
}

type B struct {
	bun.BaseModel `bun:"table:b,alias:b"`
	ID            uint `bun:"id,pk,autoincrement"`
	Value         int  `bun:",notnull"`
	AID           uint `bun:"a_id"`
}

type AWithValues struct {
	A      `bun:",extend"`
	Values int // I want to sum Bs.Value there
}

func main() {
	db := bun.NewDB(sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(os.Getenv("POSTGRESQL_ADDON_URI")))), pgdialect.New())

	_, _ = db.NewCreateTable().
		Model((*A)(nil)).
		Exec(context.Background())

	_, _ = db.NewCreateTable().
		Model((*B)(nil)).
		ForeignKey(`("a_id") REFERENCES "a" ("id") ON DELETE CASCADE`).Exec(context.Background())

	db.NewInsert().Model(&A{}).Exec(context.Background())
	db.NewInsert().Model(&B{
		AID:   1,
		Value: 1,
	}).Exec(context.Background())
	db.NewInsert().Model(&B{
		AID:   1,
		Value: 2,
	}).Exec(context.Background())

	db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))

	var a AWithValues
	if err := db.
		NewSelect().
		Model(&a).
		TableExpr("b AS b").
		Group("a.id").
		ColumnExpr(`SUM(b.value) AS a__values, a.*`).
		Relation("Bs").
		Scan(context.Background()); err != nil {
		fmt.Println(err)
	}
	fmt.Println(a)
}

I got this:

{{{} 19 []} 3}

It works but I don't have anymore Bs and if I remove TableExpr it doesnt work anymore.
I don't see what I'm doing wrong, do you have any idea ?
Thx

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

1 participant