Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto generated Incrementing field for prisma

I have created an entity called Order in my datamodel.prisma file. there it should have it's automatically generating field called orderRef. which should have an automatically generated incremental value for createOrder field of the Order entity for each mutation call.

for the first Order the value of the 'orderRef' field should be OD1, the second Order should have the value OD2 for the field 'orderRef' and so on. eg:

(OD1, OD2, ....... OD124, ..... )

What is the easiest way to achieve this? yes the value should be String, instead of Number.

like image 973
Dulara Malindu Avatar asked Mar 05 '19 10:03

Dulara Malindu


1 Answers

Currently, you cannot have auto-generated incrementing fields in Prisma. However, there is an RFC about Field Behavior that would allow this kind of feature in the future.

Currently, There are 3 alternatives:

1/ When creating your node, make a query to retrieve the last node of the same type, and increment the last value.

query {
  things(orderBy: createdAt_desc, first: 1) {
    myId
  }
}

...
newId = myId + 1
...

mutation {
  createThing(data: {myId: newId, ... }) {
    ...
  }
}

2/ When creating your node, make an aggregation query to retrieve the count of all nodes of the same type, and increment based on the count. (However, if you delete previous nodes, you may find yourself having the same value multiple time.)

query {
  thingsConnection {
    aggregate {
      count
    }
  }
}
...
newId = count + 1
...

mutation {
  createThing(data: {myId: newId, ... }) {
    ...
  }
}

3/ If what you need is a human-readable id for your user, consider creating a random 6 chars long string or using a library. (This would remove the need for an extra query, but randomness can have surprising behaviors)

like image 139
Errorname Avatar answered Oct 18 '22 02:10

Errorname