Skip to content

Commit

Permalink
chore: improve many-to-many example
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Nov 26, 2021
1 parent 1aecc81 commit 5ddb4b4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ Main features are:
Resources:

- [**Get started**](https://bun.uptrace.dev/guide/getting-started.html)
- [Discussions](https://github.com/uptrace/bun/discussions)
- [Examples](https://github.com/uptrace/bun/tree/master/example)
- [Discussions](https://github.com/uptrace/bun/discussions)
- [Newsletter](https://blog.uptrace.dev/pages/newsletter.html) to get latest updates.
- [Reference](https://pkg.go.dev/github.com/uptrace/bun)
- [Starter kit](https://github.com/go-bun/bun-starter-kit)
Expand Down
17 changes: 15 additions & 2 deletions example/rel-many-to-many/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ type Order struct {

type Item struct {
ID int64 `bun:",pk"`
// Order and Item in join:Order=Item are fields in OrderToItem model
Orders []Order `bun:"m2m:order_to_items,join:Item=Order"`
}

type OrderToItem struct {
Expand Down Expand Up @@ -59,6 +61,7 @@ func main() {
panic(err)
}
fmt.Println("Order", order.ID, "Items", order.Items[0].ID, order.Items[1].ID)
fmt.Println()

order = new(Order)
if err := db.NewSelect().
Expand All @@ -72,8 +75,18 @@ func main() {
panic(err)
}
fmt.Println("Order", order.ID, "Items", order.Items[0].ID, order.Items[1].ID)
// Output: Order 1 Items 1 2
// Order 1 Items 2 1
fmt.Println()

item := new(Item)
if err := db.NewSelect().
Model(item).
Relation("Orders").
Order("item.id ASC").
Limit(1).
Scan(ctx); err != nil {
panic(err)
}
fmt.Println("Item", item.ID, "Order", item.Orders[0].ID)
}

func createSchema(ctx context.Context, db *bun.DB) error {
Expand Down

0 comments on commit 5ddb4b4

Please sign in to comment.