Код: Выделить всё
this.prisma.$transaction(async (tx) => {
await tx.table1.create()
await tx.table2.create()
}
< /code>
Эти внутренние вызовы БД могут быть сложными, поэтому я могу захотеть для них вспомогательные функции. Тем не менее, вспомогательные функции могут быть вызваны из многих мест и могут использоваться или не использоваться внутри транзакции. Чтобы решить это, я при желании передаю транзакцию и использую ее, если она существует: < /p>
// My function with a complex default param
async createModelIfNotExists(name, color, prisma = this.prisma) {
return await prisma.upsert({...})
}
...
// Call from within transaction, and use transaction's prisma client:
this.prisma.$transaction(async (tx) => {
this.createModelIfNotExists("new model 1", "blue", tx)
...
})
// Call on its own, and it will use the prisma object attached to "this"
this.createModelIfNotExists("new model 2", "green")
Код: Выделить всё
// The default param is now instantiated in the function
async createModelIfNotExists(name, color, prisma = null) {
prisma = prisma ?? this.prisma
return await prisma.upsert({...})
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... -parameter
Мобильная версия