Lesson 14 / 35
Nested Writes: Creating Related Records Together
Create a parent with its children in one call, connect existing records, and know which ORM settings make that work.
By Rahul Agarwal · 15 years in web development
One call, several tables
Often you need to insert a user and their first post together, or attach an existing tag to a new post. Doing this by hand means inserting the parent, reading its generated ID, then inserting children with that ID. ORMs can do it for you. Prisma supports nested writes: inside data you can write posts: { create: [...] } to insert children or tags: { connect: { id } } to link existing rows, and Prisma runs the whole nested write in a transaction, so either everything is saved or nothing is. TypeORM needs cascade enabled on the relation (for example cascade: ['insert']); then saving a user whose posts array holds new post entities inserts them too. Sequelize accepts nested values in create when you also pass include naming the association, so it knows how to interpret the nested array. Without these settings, the nested data is silently ignored or rejected, which confuses many beginners.
Prisma nested create and connect
Creates a user, two posts, and links the first post to an existing tag with id 3, all in one transaction.
const user = await prisma.user.create({
data: {
email: 'ravi@example.com',
name: 'Ravi',
posts: {
create: [
{ title: 'My first post', tags: { connect: { id: 3 } } },
{ title: 'Notes on joins' },
],
},
},
include: { posts: true },
});
console.log(user.posts.length); // 2Sequelize: include the association
The include tells Sequelize that posts in the values refers to the posts association defined with as: 'posts'.
const user = await User.create(
{ email: 'ravi@example.com', name: 'Ravi', posts: [{ title: 'My first post' }] },
{ include: [{ model: Post, as: 'posts' }] },
);Quick check: In TypeORM, you save a new User whose posts array contains two new Post entities, but no posts are inserted. What is the most likely cause?
- TypeORM never saves related entities
- The relation does not have cascade enabled
- Posts must be saved before users in every case
- The DataSource has logging enabled
Answer
The relation does not have cascade enabled — Without cascade on the OneToMany relation, TypeORM does not insert related entities when saving the parent. Enable cascade for inserts or save the posts separately.