Skip to content

Commit

Permalink
docs(transactions): expand docs on relations and slices (#1200)
Browse files Browse the repository at this point in the history
  • Loading branch information
steebchen committed Feb 23, 2024
1 parent 3a507b3 commit f4252f5
Showing 1 changed file with 54 additions and 1 deletion.
55 changes: 54 additions & 1 deletion docs/pages/docs/walkthrough/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ model Comment {
}
```

## Successful scenario
## Example

A simple transaction could look as follows. Just omit the `Exec(ctx)`, and provide the Prisma calls
to `client.Prisma.Transaction`:
Expand All @@ -53,6 +53,59 @@ log.Printf("first post result: %+v", firstPost.Result())
log.Printf("second post result: %+v", secondPost.Result())
```

## Multiple transactions

If you have many transaction items or need to construct a transaction dynamically, you can use the `PrismaTransaction` type:

```go
// create two posts at once and run in a transaction
var txns []db.PrismaTransaction

for _, title := range []string{"First Post", "Second Post"} {
txn := client.Post.CreateOne(
db.Post.Published.Set(true),
db.Post.Title.Set(title),
).Tx()
txns = append(txns, txn)
}

if err := client.Prisma.Transaction(txns...).Exec(ctx); err != nil {
panic(err)
}
```

## Setting relations with foreign keys

When setting relations with foreign keys, you have to set the IDs of the related records. For example, to create a post with multiple comments, you would do the following:

```go
postID := "12345"

txns := []db.PrismaTransaction{
client.Post.CreateOne(
db.Post.Published.Set(true),
db.Post.Title.Set("First Post"),
db.Post.ID.Set(postID),
).Tx(),
client.Comment.CreateOne(
db.Comment.Content.Set("First comment"),
db.Comment.Post.Link(
db.Post.ID.Equals(postID),
),
).Tx(),
client.Comment.CreateOne(
db.Comment.Content.Set("Second comment"),
db.Comment.Post.Link(
db.Post.ID.Equals(postID),
),
).Tx(),
}

if err := client.Prisma.Transaction(txns...).Exec(ctx); err != nil {
panic(err)
}
```

## Failure scenario

Let's say we have one post record in the database:
Expand Down

0 comments on commit f4252f5

Please sign in to comment.