Can I create records based on the content of a Str...
# orm-help
a
Can I create records based on the content of a String Array? I have a Explicit Many-to-Many relation (Category and Post) and I want to create a Post and assign categorys to it based on the content of the String Array. Here the code:
Copy code
const assignCategories = await prisma.post.create({
  data: {
    title: 'First Post Title',
    categories: {
      create: [
        {
          category: {
            create: {
              name: myStringArray[0],
            },
          },
        },
        {
          category: {
            create: {
              name: myStringArray[1],
            },
          },
        },
      ],
    },
  },
})
Here the Array:
Copy code
const myStringArray = ["Category1", "Category2", "Category3"];
This is obviously a pretty bad solution because the String Array with names has no fixed size in the end and is generated by the user depending on how many categories he chooses
r
Hi @Aaron Waller - so for each post you want to create multiple categories?
you should be able to use the `createMany inside your `create`` :
Copy code
const assignCategories = await prisma.post.create({
  data: {
    title: 'First Post Title',
    categories: {
      createMany: myStringArray.map(cat => ({
              name: myStringArray[0],
            }),
    },
  },
})
I think it may be something like that ..
a
The docs say • ā€œ*Not* available in the context of a many-to-many relation - for example, you cannot
prisma.post.create(...)
a post and use a nested
createMany
to create categories (many posts have many categories). ā€ And unfortunately this is not working
I solved it:
Copy code
const assignCategories = await prisma.post.create({
    data: {
        title: 'First Post Title',
        categories: {
            create: myStringArray.map((title) => ({
                category: { create: { title } },
            })),
        },
    },
});
šŸ‘ 1