diff --git a/packages/medusa/src/repositories/product.ts b/packages/medusa/src/repositories/product.ts index 46e01c29bb..dd1dc83c8f 100644 --- a/packages/medusa/src/repositories/product.ts +++ b/packages/medusa/src/repositories/product.ts @@ -6,9 +6,17 @@ import { Product } from "../models/product" export class ProductRepository extends Repository { public async findWithRelations( relations: Array = [], - optionsWithoutRelations: Omit, "relations"> = {} + idsOrOptionsWithoutRelations: Omit< + FindManyOptions, + "relations" + > = {} ): Promise { - const entities = await this.find(optionsWithoutRelations) + let entities + if (Array.isArray(idsOrOptionsWithoutRelations)) { + entities = await this.findByIds(idsOrOptionsWithoutRelations) + } else { + entities = await this.find(idsOrOptionsWithoutRelations) + } const entitiesIds = entities.map(({ id }) => id) const groupedRelations = {} diff --git a/packages/medusa/src/services/product.js b/packages/medusa/src/services/product.js index 38b3fb4696..efc7fabde1 100644 --- a/packages/medusa/src/services/product.js +++ b/packages/medusa/src/services/product.js @@ -80,7 +80,7 @@ class ProductService extends BaseService { * @param {Object} listOptions - the query object for find * @return {Promise} the result of the find operation */ - list(selector = {}, config = { relations: [], skip: 0, take: 20 }) { + async list(selector = {}, config = { relations: [], skip: 0, take: 20 }) { const productRepo = this.manager_.getCustomRepository( this.productRepository_ ) @@ -101,7 +101,7 @@ class ProductService extends BaseService { query.select = config.select } - const rels = query.relations + let rels = query.relations delete query.relations if (q) { @@ -110,27 +110,27 @@ class ProductService extends BaseService { delete where.description delete where.title - query.join = { - alias: "product", - leftJoinAndSelect: { - variant: "product.variants", - collection: "product.collection", - }, - } - - query.where = qb => { - qb.where(where) - - qb.andWhere( + const raw = await productRepo + .createQueryBuilder("product") + .leftJoinAndSelect("product.variants", "variant") + .leftJoinAndSelect("product.collection", "collection") + .select(["product.id"]) + .where(where) + .andWhere( new Brackets(qb => { - qb.where(`product.title ILIKE :q`, { q: `%${q}%` }) - .orWhere(`product.description ILIKE :q`, { q: `%${q}%` }) + qb.where(`product.description ILIKE :q`, { q: `%${q}%` }) + .orWhere(`product.title ILIKE :q`, { q: `%${q}%` }) .orWhere(`variant.title ILIKE :q`, { q: `%${q}%` }) .orWhere(`variant.sku ILIKE :q`, { q: `%${q}%` }) .orWhere(`collection.title ILIKE :q`, { q: `%${q}%` }) }) ) - } + .getMany() + + return productRepo.findWithRelations( + rels, + raw.map(i => i.id) + ) } return productRepo.findWithRelations(rels, query)