is there a way to use if conditions inside a query...
# orm-help
j
is there a way to use if conditions inside a query? for example:
Copy code
return this.prisma.user.findMany({
      where: {
        AND: [
if (searchUserDto.dni) { dni: { contains: searchUserDto.dni } },
if (searchUserDto.name) { name: { contains: searchUserDto.name} },
if (searchUserDto.surname) { surname: { contains: searchUserDto.surname} },
if (searchUserDto.email) { email: { contains: searchUserDto.email } },
if (searchUserDto.status) { status: { equals: searchUserDto.status.toString() != 'true' ? false : true } },
if (searchUserDto.bas_role_id) { bas_role_id: { equals: (searchUserDto.bas_role_id) } }
        ]
      }
    });
🙌 1
e
Try this:
Copy code
return this.prisma.user.findMany({
      where: {
        AND: [
...(searchUserDto.dni && { dni: { contains: searchUserDto.dni } }),
...(searchUserDto.name && { name: { contains: searchUserDto.name} }),
...(searchUserDto.surname && { surname: { contains: searchUserDto.surname} }),
...(searchUserDto.email && { email: { contains: searchUserDto.email } }),
...(searchUserDto.status && { status: { equals: searchUserDto.status.toString() != 'true' ? false : true } }),
...(searchUserDto.bas_role_id && { bas_role_id: { equals: (searchUserDto.bas_role_id) } })
        ]
      }
    });
💯 1
n
I haven’t validated it but I actually think that
contains
works in the way that if the supplied value is
null
, no filter is being applied. So these null checks should not actually be necessary.
e
@nikolasburk Is there a way to validate it for contains and other fields? I am using many null checks and would be happy to get rid of them if they are not necessary
j
@nikolasburk yes, on string fields "contains" works very well, if the condition is null then it doesn't apply the filter. But on boolean, number etc fields there's no "function" like contains