hello, I have a raw query (postgres) here with an ...
# orm-help
d
hello, I have a raw query (postgres) here with an
ORDER BY
Copy code
this.prisma.$queryRaw`
	SELECT *
	FROM "public"."OrderStatus"
	INNER JOIN "public"."OrderStatusDescription" ON ("public"."OrderStatus"."id" = "public"."OrderStatusDescription"."orderStatusId")
	WHERE "public"."OrderStatusDescription"."languageId" = ${languageId}
	ORDER BY "public"."OrderStatusDescription"."name" DESC LIMIT ${pagination.take} OFFSET ${pagination.skip}
`
the moment I have a variable instead of hardcoded
DESC
the query doesnt work.
Copy code
ORDER BY "public"."OrderStatusDescription"."name" ${order.toUpperCase()} // order = 'asc' | 'desc'
same thing happens with parameterized queries
d
could you log out the string that is created for the query? eg
SELECT …
it might not be removing the speech marks causing
'ASC'
instead of
ASC
d
there's no extra quotes around it
d
languageid looks like it is in the wrong format
its not being interpreted as a string
Copy code
WHERE "public"."OrderStatusDescription"."languageId" = "${languageId}"
d
dont think that matters much. though it still doesnt work
same error on the same place
d
hmmm, I’m not sure how I can help you. @Ryan could help maybe
have you tried without converting to uppercase?
d
no 😞
i need nested sort on
OrderStatusDescription
table but prisma doesnt support this so I want to do it with a raw query
r
You would need to do something like this for adding
asc
or
desc
dynamically:
Copy code
await prisma.$queryRaw`select * from table order by field ${
      order === 'desc' ? Prisma.sql`desc` : Prisma.sql`asc`
}`
d
yes thanks, that works! by why didnt this work
Copy code
${Prisma.sql`${order}`}
also, I am trying to selected the field dynamically
Copy code
ORDER BY "public"."OrderStatusDescription"."name"
example
Copy code
ORDER BY "public"."OrderStatusDescription"."${orderBy}"
but I keep getting
column doesnt exists
. how would I solve this one?
@Ryan
r
yes thanks, that works! by why didnt this work
Raw query support is based on this library and whatever you interpolate inside is taken as a value, which is why you need to do this.
also, I am trying to selected the field dynamically
That’s tricky. I would need to check for this.
This would work, but you need to sanitise the field first:
Copy code
let order = 'desc'
let field = 'id'

await prisma.$queryRaw`select * from User order by ${Prisma.raw(field)} ${
  order === 'desc' ? Prisma.sql`desc` : Prisma.sql`asc`
}`
d
thanks! it works fine like this
${Prisma.raw(orderBy)}
👍 1