Restrict and ignore associated field in typeorm

I need help in restricting the related data when querying using query builder. Here is the code I have for fetching employee orders:

import { getRepository, Repository } from "typeorm";

public async findEmployeeQuery(id : number) {
    try {
        let query = await getRepository(Employees)
        .createQueryBuilder('employee')
        .where('employee.id = :id' , {id})
        .leftJoinAndSelect('employee.customers' , 'customers')
        .getOne()
        const user = query
        return user
    } catch (error) {
        throw error
    }

}

Now I want to control the number of customers returned for each request - is there a way to do that?

I experimented with the limit and skip options, but they only seem to work for the employee entity and not for the related data.

Answer №1

To narrow down the list of customers, you will need to run an additional query:

import { getRepository, Repository } from "typeorm";

public async fetchEmployeeInformation(id : number) {
    try {
        let employeeData = await getRepository(Employees)
        .createQueryBuilder('employee')
        .where('employee.id = :id' , {id})
        .getOne()

        employeeData.customers = await getRepository(Customers)
        .createQueryBuilder('customer')
        .where('customer.employee= :id' , {user.id})
        .limit(10) // specify the limit here
        .getMany()

        return employeeData;
    } catch (error) {
        throw error
    }
}

Answer №2

I have devised a neat solution for this issue...

This could be beneficial for others as TypeORM currently lacks support for pagination in relations (fingers crossed for future updates! =) )

 let category: any = await Category.findOne({
      where: {
        id: id,
      },
    });
    // searching for products associated with that category
    let products = await orm
      .createQueryBuilder("products", "p")
      .innerJoinAndSelect("p.categories", "c", "c.id = :categoryId", {
        categoryId: id,
      })
      // incorporating pagination
      .skip(offset)
      .take(limit)
      .getMany();
    // Connecting the array to the Category Object
    category.products = products;

Answer №3

import { getRepository, Repository } from "typeorm";

public async retrieveEmployeeData(id : number) {
    try {
        let employeeData = await getRepository(Employees)
        .createQueryBuilder('employee')
        .where('employee.id = :id' , {id})
        .leftJoinAndSelect('employee.customers' , 'customers')
        .take(4) // limits to 4 records
        .skip(5) // offset by 5 entities
        .getOne()

        return employeeData
    } catch (error) {
        throw error
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: There was a problem trying to import the `.d.ts` file

Software Stack Vue version 3.2.19 @vue/test-utils version 2.0.0-rc.15 Typescript version 4.1.6 Issue Description Encountering an error when running the command vue-cli-service test:unit --no-cache. Please refer to the TypeError screenshot (link to Con ...

Error importing Firestore in Firebase Cloud Function

As I work on my cloud function, Firebase Firestore gets automatically imported in the following way: import * as functions from 'firebase-functions'; import { QuerySnapshot } from '@google-cloud/firestore'; const admin = require(&ap ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Navigational menu routing with AngularJS2 using router link paths

Currently, I am working on developing a navigation menu using angularJS2. Here is the snippet from my app.component.ts: import {provide, Component} from 'angular2/core'; import {APP_BASE_HREF, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, HashLocati ...

The Sanity npm package encounters a type error during the build process

Recently, I encountered an issue with my Next.js blog using next-sanity. After updating all npm packages, I found that running npm run build resulted in a type error within one of the dependencies: ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 ...

Encountering incorrect month while utilizing the new Date() object

My Objective: I am looking to instantiate a new Date object. Snippet of My Code: checkDates (currentRecSec: RecommendedSection){ var currActiveFrom = new Date(currentRecSec.activeFrom.year,currentRecSec.activeFrom.month,currentRecSec.activeFrom.day ...

Is TypeScript declaration merging not functioning properly?

Trying to enhance an existing interface with a new member is causing Typescript errors for me. // foo.js export interface IOption { xOffset: number } import {IOption} from 'foo'; // Attempting to extend IOption with `yOffset`, but encounter ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Utilize array mapping to alter the complete object

In my project using TypeScript (Angular 2), I am working on creating a "reset" method for an object array: cars [ { id: 1, color: white, brand: Ford, model: Mustang, ... }, ... ] Users have the ability to modify these objects, ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

When it comes to passing prop values through functions, TypeScript types do not provide suggestions

I'm struggling to find a way to ensure that developers have suggested types for specific props in my component, regardless of how they pass data to the prop. For example, when I directly pass an array of values to the prop: <Component someProp={[{ ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Is it possible to utilize BE-provided Enum in the FE and if so, how can

How can I utilize the Enum from BE in an HTML template? Should I use it as is, or provide another one in FE? What is considered best practice? export interface UserModel { id?: number; email?: string; password?: string; gender?: UserModel ...

Troubleshooting issue with React and Material UI Table pagination display

Issue with Material UI Table Display When Changing Pages When receiving an array of Artist Objects through props to create a checklist table, I encounter some display issues. The table works fine initially, but when changing pages or sorting, more rows th ...

Troubleshooting Angular: Issues with Table Data Display and Source Map Error

I'm currently tackling a challenge in my Angular application where I am unable to display data in a table. When I fetch data from a service and assign it to a "rows" variable within the ngOnInit of my component, everything seems to be working fine bas ...

What is the best way to use form input to filter an Observable?

Within my component, I have declared the variable "countries$": countries$!: Observable<Country[]>; To populate this variable with data from this API, I use the following code in the "ngOnInit" lifecycle hook: ngOnInit(){ this.countries$ ...