prisma

Accessing models by using a variable


How can I dynamically access a model in prisma?

return await prisma[modelName].create({ data })

... seems not to work.

I am looking for a way to access my models by using a variable. How can this be done?


Update:

There is a typescript error: Unable to compile TypeScript.

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.
  No index signature with a parameter of type 'string' was found on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.

Solution

  • This is a bit hacky but you can use // @ts-ignore above the line to avoid the error you mentioned.

    This should work fine:

    // @ts-ignore
    return await prisma[modelName].create({ data });
    

    I fully understand there should be a better way to do this. However this is by far the simplest way without resorting to private APIs.