WatermelonDB
WatermelonDB copied to clipboard
Create parent and child in a single batch
Hello,
I would like to create initial data from a template. But I want it to be transactional, I don't want to have only the parent then a failure, or only a part of the children.
So far I have done this and it seems to work:
function createFromTemplate(database: Database, index: number) {
const template: Template = TEMPLATES[index]
return database.write(async () => {
const posts = await database.get('posts')
const comments = await database.get('comments')
const postOp = posts.prepareCreate((post) => {
post.name = template.name
post.steps = template.steps
})
const commentOps = template.comments.map(raw => comments.prepareCreate((comment) => {
comment.name = raw.name
comment.step = raw.step
comment.post.set(postOp._raw)
}))
await database.batch([postOp, ...commentOps])
})
}
But I am not sure of the correctness. Will that be transactional? Notably, usage of _raw seems off.
Thank you.