Create nested record. - How can i get another rela...
# orm-help
y
Create nested record. - How can i get another relation record id? https://www.prisma.io/docs/concepts/components/prisma-client/crud#create-a-deeply-nested-tree-of-records this is simplified version
Copy code
const u = await prisma.user.create({
  data: {
    email: 'emma@prisma.io',
    posts: {
      create: [
        {
          title: 'My first post',
          external_user_id: `a1b2c34d-{user.id}`
        }
      ],
    },
  },
})
about
external_user_id
, so how can i get user.id (that is being created in this query) dynamically?
✅ 1
s
If I understand the query correctly, it looks like you are trying to create a
user
and at the same time create a
post
with the related user’s
id
as the
external_user_id
. Check out the example here. Let me know if that helps!
y
hi @Sabin Adams, thanks for the update. your understanding is correct. unfortunately, i couldn't find the answer i was looking for in the reference
s
If you run a query like this:
Copy code
const user = await prisma.user.create({
  data: {
    email: 'yvette@prisma.io',
    posts: {
      create: [
        { title: 'How to make an omelette' }
      ],
    },
  }
})
You don’t need to worry about populating the
external_user_id
, it will be filled automatically as long as it is the defined relation field in your Prisma schema
y
problem is
external_user_id
is not the same as
id
id
would be
12
something like that which prisma nicely handles but extenal_user_id contains arbitrary string handler so would look like
asdije-12
and this arbitrary handler changes per new post.
s
Ah my bad, I misunderstood. In that case, it would likely need to be done in two operations:
Copy code
const user = await prisma.user.create({
  select: {
    id: true,
    posts: {
      select: {
        id: true
      }
    }
  },
  data: {
    email: 'test@gmail.com',
    posts: {
      create: {
        title: 'Test'
      }
    }
  }
})

await prisma.post.update({
  where: { id: user.posts[0].id },
  data: { external_user_id: `asd-${user.id}`}
})
There are of course safeguards you’d want to put in place to ensure you’re updating the correct post and the post actually exists, but that’s the general gist
y
ah i see. i was hoping to know on one query. but if that needs to be split into 2 operations, that works, as well. thanks!
thanks for the quick reply! 🙏
s
No problem, glad I could help!