diff --git a/internal/dbtest/orm_test.go b/internal/dbtest/orm_test.go index fcd1b3931..6048cafef 100644 --- a/internal/dbtest/orm_test.go +++ b/internal/dbtest/orm_test.go @@ -32,6 +32,7 @@ func TestORM(t *testing.T) { {testM2MRelationExcludeColumn}, {testRelationBelongsToSelf}, {testCompositeHasMany}, + {testCompositeM2M}, } testEachDB(t, func(t *testing.T, dbName string, db *bun.DB) { @@ -441,6 +442,78 @@ func testCompositeHasMany(t *testing.T, db *bun.DB) { require.Equal(t, 2, len(department.Employees)) } +func testCompositeM2M(t *testing.T, db *bun.DB) { + type Item struct { + ID int64 `bun:",pk"` + ShopID int64 `bun:",pk"` + } + + type Order struct { + ID int `bun:",pk"` + ShopID int `bun:",pk"` + Items []Item `bun:"m2m:orders_to_items,join:Order=Item"` + } + + type OrderToItem struct { + bun.BaseModel `bun:"table:orders_to_items"` + + ShopID int `bun:""` + + OrderID int `bun:""` + Order *Order `bun:"rel:belongs-to,join:shop_id=shop_id,join:order_id=id"` + ItemID int `bun:""` + Item *Item `bun:"rel:belongs-to,join:shop_id=shop_id,join:item_id=id"` + } + + db.RegisterModel((*OrderToItem)(nil)) + mustResetModel(t, ctx, db, (*Order)(nil), (*Item)(nil), (*OrderToItem)(nil)) + + items := []Item{ + {ID: 1, ShopID: 22}, + {ID: 2, ShopID: 22}, + {ID: 3, ShopID: 22}, + } + _, err := db.NewInsert().Model(&items).Exec(ctx) + require.NoError(t, err) + + orders := []Order{ + {ID: 12, ShopID: 22}, + {ID: 13, ShopID: 22}, + } + _, err = db.NewInsert().Model(&orders).Exec(ctx) + require.NoError(t, err) + + orderItems := []OrderToItem{ + {OrderID: 12, ItemID: 1, ShopID: 22}, + {OrderID: 12, ItemID: 2, ShopID: 22}, + {OrderID: 13, ItemID: 3, ShopID: 22}, + } + _, err = db.NewInsert().Model(&orderItems).Exec(ctx) + require.NoError(t, err) + + var ordersOut []Order + + err = db.NewSelect(). + Model(&ordersOut). + Where("id = ?", 12). + Relation("Items"). + Scan(ctx) + require.NoError(t, err) + require.Equal(t, 1, len(ordersOut)) + require.Equal(t, 2, len(ordersOut[0].Items)) + + var ordersOut2 []Order + + err = db.NewSelect(). + Model(&ordersOut2). + Where("id = ?", 13). + Relation("Items"). + Scan(ctx) + require.NoError(t, err) + require.Equal(t, 1, len(ordersOut2)) + require.Equal(t, 1, len(ordersOut2[0].Items)) +} + type Genre struct { ID int `bun:",pk"` Name string