Gezim
07/05/2022, 6:27 AMPrimsa.$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?Gezim
07/05/2022, 6:42 AMconst 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')
nikolasburk
$queryRaw
.nikolasburk
Gezim
07/05/2022, 10:35 AM