Does `Primsa.$queryRaw` allow me to compose a quer...
# orm-help
g
Does
Primsa.$queryRaw
allow me to compose a query string based on a few criteria? With TypeORM, I’m using a query builder and adding
leftJoinAndSelect
where
groupBy
all conditionally. How would I do that in Prisma?
1
This is the gnarly query I’m trying to build in Prisma:
Copy code
const builder = this.recipeRepository.createQueryBuilder('r');

builder.where('r.store = :storeId', { storeId });

let groupBy = '1';
if (sessionId) {
  builder.leftJoinAndSelect('r.ratings', 'rs', 'rs.sessionId = :sessionId', { sessionId });
  groupBy = '(1, rs.id)'; // rs.id is needed in group by for some reason: column "rs.id" must appear in the GROUP BY clause or be used in an aggregate function at character.
}

builder.groupBy(groupBy);

let filterIds = options.filterIds;

if (options.filters) {
  filterIds = filterOptions.map((option) => option.id);
}

if (filterIds) {
  builder.innerJoin('r.filters', 'rfo');

  /**
   * Here I tried to create a query that allows us to intersect the results for different filters based on filter label.
   * For example, if user selects Halal, Gluten-Free from Diet filter and Breakfast and Lunch from Meal Type filter, then
   * the query should be (Halal or Gluten-Free) and (Breakfast or Lunch).
   * This query is essentially from here: <https://stackoverflow.com/a/58946309/32495>
   */

  const distinctFilterQuery = this.recipeFilterOptionRepository
    .createQueryBuilder('o')
    .select('ARRAY_AGG(DISTINCT o."filterId")')
    .where(`o.slug in (:...slugs)`, { slugs: filterIds });

  builder
    .andWhere(`rfo.slug in (:...filterIds)`, { filterIds })
    // this will create an array with all the filters (not options) a recipe has,
    // and then compare it with an array of all the filters (not options) we need.
    .having(`ARRAY_AGG(DISTINCT rfo."filterId") = (${distinctFilterQuery.getQuery()})`)
    .setParameters(distinctFilterQuery.getParameters());
}

if (options.search) {
  builder.andWhere('r.name ilike :search', {
    search: `%${options.search}%`,
  });
}

if (typeof options.draft === 'boolean') {
  builder.andWhere('r.draft = :draft', { draft: options.draft });
}

builder.loadRelationIdAndMap('filters', 'r.filters').orderBy('r."createdAt"', 'DESC')
n
Unfortunately I don’t think you get the same mix of a “query API” with “raw SQL” in Prisma Client at the moment, it sounds like you’re probably looking for something like this? https://github.com/prisma/prisma/issues/5560 In Prisma at the moment, you can only submit entire SQL strings to
$queryRaw
.
Just an idea: Does your current query builder allow you just “emit” the SQL code for a query that you build instead of sending it to the DB. In that case, you could “build” the query with that query builder but send it to the DB using Prisma Client…
👍 1
g
@nikolasburk That’s a great idea. Thanks!
🙌 1