#using `set: []` and `connectOrCreate` in one query

1 messages · Page 1 of 1 (latest)

exotic wraith
#

I have an update query to my table:

prisma.table.update({
  where: { id: baseID },
  data: {
    materials: {
      set: [],
      connectOrCreate: parsedData.materials.map((element) => ({
    where: { id: element.id },
    create: { id: element.id, title: element.title }
      }))
    }
  }
})

I am using set: [] and connectOrCreate: [...] in the same query and it seems to matter what order I supply those options.
Is that intended use? Or should I avoid doing it like this?

#

I mean, the funny thing is: when I use set: [], connectOrCreate: [a,b,c], then it works as expected: all connections are removed and then a, b, c are connected.

#

When I swap them to be connectOrCreate: [a,b,c], set: [], then I always end up with an empty list (= no connections).

#

My problem with this is that it seems that JS does not guarantee that object keys stay in the order of insertion, so I might end up in an undefined state.

#

I am not super familiar with Prisma, is there maybe another way to have connectOrCreateAndDeleteAllPreviousConnections/setAndCreateIfMissing without having to run multiple queries/use a transaction?

exotic wraith
#

Does anyone know about this?

bitter stone
#

I asked your question to our new #🧠│ask-ai and got the following reply:
Yes, the order of operations in Prisma does matter when using set and connectOrCreate in the same query.

In a GitHub discussion, a user asked a similar question about the execution order of set and connect. The response indicated that the order of operations does indeed affect the outcome.

In the first case, where set is used before connect, the user is connected with all the roles from the roles array. However, in the second case, where set is used after connect, the user is not connected with any of the roles as set:[] would clear all the connected records.

Therefore, in your case, if you use set: [] before connectOrCreate, it will first clear all the connections and then establish new ones based on the connectOrCreate operation. If you use set: [] after connectOrCreate, it will first establish the connections and then clear them all.

So, the order in which you use these operations depends on the specific behavior you want to achieve. If you want to clear all existing connections and then establish new ones, use set: [] before connectOrCreate. If you want to establish new connections and then clear them all, use set: [] after connectOrCreate.

GitHub

public static async update(user) { let result = await prisma.user.update({ where: { id: user.id }, data: { roles: { set: [], connect: user.roles.map((e) => ({ id: e.id })) }, }, }); } what is th...

exotic wraith
#

oh ok. Is this reliable? I thought ECMA does not guarantee anything with regards to the order of properties of POJOs.