I've got a pretty simple question. Is there a way ...
# orm-help
j
I've got a pretty simple question. Is there a way when creating a row that I can set the relation company by doing
Copy code
customerId: 12
instead of
Copy code
customer: { connect: { id: 12 } }
r
Yes you can if it’s not a many side of the relation.
j
Im not quite sure Ii got that? Rn my solution is a script that transforms any keys that end on Id to the connect object
r
Could you share your schema?
j
Copy code
t.field('createVisit', {
      type: Visit.$name,
      args: {
        data: nonNull(
          arg({
            type: 'VisitInput',
          }),
        ),
      },
      resolve: async (_, args, context: Context) => {
        const latestVisits = await context.prisma.visit.findMany({
          orderBy: {
            createddate: 'desc'
          },
          take: 1
        })

        const data: Record<string, any> = args.data

        renameEntry(data, 'productCategoryId', 'categoryId')
        renameEntry(data, 'technicianId', 'employeeId')

        const caseNumber: number = latestVisits && latestVisits[0] && latestVisits[0].caseNumberInt ? Number(latestVisits[0].caseNumberInt) + 1 : 1
        const newVisit = await context.prisma.visit.create({
          data: {
            createddate: new Date(),
            caseNumber: "P01-" + caseNumber.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false}),
            caseNumberInt: caseNumber,
            company: { connect: { id: context.user.company }},
            ...fixRelations(data),

          },
        })

        await context.pubsub.publish('visitCreated', newVisit)
        return newVisit
      },
    })
renameEntry just adapts what the fields are called in nexus vs prisma. fixRelations is the script i described beforehand
Copy code
export const fixRelations = (oldObj: Record<string, any>) => {
  const obj = oldObj

  Object.keys(obj).forEach(key => {
    if(key.endsWith('Id')) {
      let value
      if(!obj[key]) value = undefined
      else value = { connect: { id: obj[key] } }
      obj[key.slice(0, -2)] = value
      delete obj[key]
    }
  })

  return obj
}
r
Are there other relations as well that use
connect
or
create
? If so this will not work. You cannot mix
connect
and specifying the
id
directly. You can only use one of them.
j
All og Them uset id and it errored
r
What’s the error?