I have two interconnected models, I'll oversimplif...
# orm-help
h
I have two interconnected models, I'll oversimplify them:
Copy code
model Wallet {
  user User
  balance Int
  transactions Transaction[] 
}

model Transaction {
  id Int 
  change Int
  wallet Wallet 
}
and now, I want to make a query that: creates a Transaction and increments the connected
wallet.balance
by the
change
, but I have no idea if it's even possible.
1
n
Hey Hubert, thanks for your question! This should work with a nested query starting at
prisma.wallet
like so:
Copy code
const walletId = 42
const changeValue = 100
const updatedWallet = await prisma.wallet.update({
  where: {
    id: walletId
  },
  data: {
    balance: {
      increment: changeValue
    },
    transactions: {
      create: {
        change: changeValue
      }
    }
  }
})
If you want the newly created
Transaction
object to be returned as well you can use
include
in the query:
Copy code
const updatedWallet = await prisma.wallet.update({
  where: {
    id: walletId
  },
  data: {
    balance: {
      increment: changeValue
    },
    transactions: {
      create: {
        change: changeValue
      }
    }
  },
  include: {
    transactions: true
  }
})
h
Ok, that seems reasonable. Thank you 🙇
🙌 1
n
Hope this works, let me know if you have any further questions 😄
h
@nikolasburk and considering such models:
Copy code
model Wallet {
  user User
  balance Int
  incomingTransactions Transaction[] @relation("incomingTransaction")
  outgoingTransactions Transaction[] @relation("outgoingTransaction")
}

model Transaction {
  id Int 
  change Int
  toWallet Wallet @relation(name: "incomingTransaction")
  fromWallet Wallet? @relation(name: "outgoingTransaction")
}
how can I create a query that creates a Transaction and: 1. decrements balance of fromWallet by
change
if specified 2. increments balance of toWallet by
change
3. and actually returns Transaction
or should I just try to change the models?