"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship:

// Branch entity
 @ManyToMany(
        (type) => User,
        (e) => e.branches
    )
    users: User[];


// User entity
   @ManyToMany(
        (type) => Branch,
        (e) => e.users,
        {   eager: true,
            cascade: false }
    )
    
    @JoinTable()
    branches: Branch[];


    @IsEnum(Role)
    @Column('text', { default: Role.Client })
    role: Role;

I am looking to find branches where the users list does not contain a user with the role 'client'.

This functionality is needed for the following scenario:

[
 Branch {
    id: '98007770-c924-43cd-988c-774492e1e759',
    name: 'poslovnica1',
    users: [ {role:'client'},{role:'superAdmin'} ]
  },
 Branch {
    id: '787007770-c924-43cd-988c-774492e1e759',
    name: 'poslovnica13',
    users: [ {role:'client'},{role:'superAdmin'} ]
  },

  Branch {
    id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
    name: 'poslovnica2',
    users: [ {role:'superAdmin' }]
  }
]

After filtering, the desired result is to retrieve all branches that do not have a user with the role 'client' or 'superAdmin':

[
   Branch {
    id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
    name: 'poslovnica2',
    users: [ {role:'superAdmin'} ]
  }
]

Answer №1

I was able to achieve a similar result using lodash, but approached it differently:

await branchRepository.find({
                    join: {
                        alias: 'branch',
                        leftJoinAndSelect: {
                            users: 'branch.users'
                        }
                    },
                    where: (qb) => {
                        qb.where('role != :role', { role: 'client' });
                    }
                });

However, my goal is to filter branches by users, not just users. Thanks for your effort!

Answer №2

Welcome to the world of coding!

You were so close! Why not give this code a shot using lodash:

import {values, omit} from 'lodash';

// ....

const notClientRoles = values(omit(Role, Role.Client));

await this.branchRepository
    .createQueryBuilder('b')
    .leftJoin('b.users', 'users')
    .where('users.client IN(:...roles)', { roles: notClientRoles })
    .getMany(); 

Here are the details:

const notClientRoles = values(omit(Role, Role.Client))

This code snippet helps remove the Client role from the list using values and omit methods from lodash. We then use it in the where clause like so:

    .where('users.client IN(:...roles)', { roles: notClientRoles })

Let me know if this solution works for you :)

Answer №3

My desires are always fulfilled:

 result = await this.branchRepository.find({ relations: ['users'] });
 result = result.filter((branch: Branch) => {
                if (!branch.users.some((user) => user.role === Role.Client)) return branch;
                });

I am continually seeking ways to enhance this process...

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

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

What is the proper way to specify the type for a proxy that encapsulates a third-party class?

I have developed a unique approach to enhancing Firestore's Query class by implementing a Proxy wrapper. The role of my proxy is twofold: If a function is called on the proxy, which exists in the Query class, the proxy will direct that function call ...

Issue with Typescript flow analysis when using a dictionary of functions with type dependency on the key

I am utilizing TypeScript version 4.6 Within my project, there exists a type named FooterFormElement, which contains a discriminant property labeled as type type FooterFormElement = {type:"number",...}|{type:"button",...}; To create instances of these el ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

The SunEditor onChange event does not reflect updated state information

software version next: 12.0.7 suneditor: 2.41.3 suneditor-react: 3.3.1 const SunEditor = dynamic(() => import("suneditor-react"), { ssr: false, }); import "suneditor/dist/css/suneditor.min.css"; // Import Sun Editor's CSS Fi ...

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...

The 'doRequest' property is not found on the type 'any[]'

Attempting to develop a custom hook in TypeScript for managing errors & API requests, but encountering a type error where a property does not exist on type 'any[]' Here is the code for the hook: import axios from 'axios'; import { ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

Boosting the performance of SELECT queries in a sizable PostgreSQL database with 250 million rows

My PostgreSQL database holds a very large table with approximately 250 million rows, consisting of the following 4 attributes: CREATE TABLE public.sim_values_english ( id bigint NOT NULL DEFAULT nextval('sim_values_english_id_seq'::regclass), ...

MikroORM - Conditional join without foreign key constraints on the ID

I came across a rather peculiar database schema that includes a jsonb field with userId and userType attributes, along with two different user tables for distinct user types. The selection of the table to join based on the userType is crucial. Although I ...

Tips for locating precise information within nested object formations using Javascript

Within my code, I have showcased two distinct types of response. Upon closer examination of the following code snippets, it becomes evident that the structure of the response from a service differs slightly between the two types. In the first type, there i ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

Issue encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

How can we make type assertions consistent without sacrificing brevity?

In the project I am currently working on, we have implemented a warning for typescript-eslint/consistent-type-assertions with specific options set to { assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }. While I generally appr ...

Can we verify if strings can serve as valid property names for interfaces?

Let's consider an interface presented below: interface User { id: string; name: string; age: number; } We also have a method defined as follows: function getUserValues(properties:string[]):void { Ajax.fetch("user", properties).then( ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...