6

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.

Dulara Malindu
  • 1,477
  • 4
  • 18
  • 37

1 Answers1

4

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)

Dulara Malindu
  • 1,477
  • 4
  • 18
  • 37
Errorname
  • 2,228
  • 13
  • 23
  • Thank you.! I also spent a considerable amount of time searching for an answer on this issue. I believe in your first solution as the best solution that is currently available. Since the client can delete existing orders I can't use the second solution although it seems the easiest one to implement. and our system will have considerable amount of orders. 6 letter random string might not suit. I decided to continue with your first answer. – Dulara Malindu Mar 14 '19 at 04:56