Skip to content

Commit

Permalink
feat: add test for M2M relations with composite keys
Browse files Browse the repository at this point in the history
  • Loading branch information
ygabuev committed Jun 5, 2024
1 parent 1e623bd commit 708ab34
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions internal/dbtest/orm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func TestORM(t *testing.T) {
{testM2MRelationExcludeColumn},
{testRelationBelongsToSelf},
{testCompositeHasMany},
{testCompositeM2M},
}

testEachDB(t, func(t *testing.T, dbName string, db *bun.DB) {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 708ab34

Please sign in to comment.