uptrace / bun

SQL-first Golang ORM

Home Page:https://bun.uptrace.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom sum column on a relation

thecampagnards opened this issue · comments

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