Is there a way to locate a model using a value within a OneToMany connection?

I am trying to develop a function to retrieve a user model based on a specific value within a OneToMany relationship.

Below is the function in question:

async getUserViaPlatform(provider: string, id: string) {
        return await this.webUserRepository.findOne({
            profiles: [{
                provider,
                platformID: id
            }]
        });
    }

The structure of the User model is as follows:

@Entity()
export class WebUser {
    @PrimaryGeneratedColumn()
    id!: number;

    @Column()
    name!: string;

    @Column({ nullable: true })
    picture?: string;

    @OneToMany(type => WebProfile, webProfile => webProfile.user, { eager: true })
    profiles!: WebProfile[];

    @CreateDateColumn()
    createdAt!: Date;

    @UpdateDateColumn()
    updatedAt!: Date;
}

The "WebProfile" model looks like this:

@Entity()
export class WebProfile {
    @PrimaryGeneratedColumn()
    id!: number;

    @Column()
    provider!: string;

    @Column()
    email!: string;

    @Column()
    platformID!: string;

    @ManyToOne(type => WebUser, user => user.profiles)
    user!: WebUser;

    @CreateDateColumn()
    createdAt!: Date;

    @UpdateDateColumn()
    updatedAt!: Date;
}

My goal is to retrieve a user where a profile matches the provided provider and ID. However, currently, the function only returns the first user regardless of the input.

Answer №1

To execute a query with both QueryBuilder and a join, follow these steps:

await this.webUserRepository.createQueryBuilder('webUser')
    .leftJoinAndSelect('webUser.profiles', 'profile')
    .where   ('profile.provider   = :provider', { provider: '...' })
    .andWhere('profile.platformID = :platformID', { platformID: '...' })
    .getOne();

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

Develop a versatile factory using Typescript

For my current project, I am developing a small model system. I want to allow users of the library to define their own model for the API. When querying the server, the API should return instances of the user's model. // Library Code interface Instanc ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

Which is better suitable in TypeScript generics: void, never, or undefined?

Curious about this topic. I am seeking a definitive answer to clarify my understanding. My goal is to specify to the compiler/language service/reader that T should be absolutely nothing, empty, or null. I am unsure whether void, never, or undefined is the ...

Using the `window` object in Jasmine with Angular, a mock can be created for testing purposes

In my current project, I have a function that I need to write unit tests for. Within this function, I am comparing the global objects window and parent using const isEqual = (window === parent). I am wondering what would be the most effective way to mock ...

Is it possible to import node_modules from a specific directory mentioned in the "main" section of the package.json file?

Is it feasible to import from a source other than what is defined by the "main" setting? In my node_modules-installed library, the main file is located at lib/index.js With es2015 imports (source generated from ts compiled js), I can use the following ...

JavaScript Class Emit Signal for establishing a sequence of interconnected events

My Vue project includes a JavaScript class specifically for mobile devices. I'm looking to have this class emit a signal once the property 'hasEnded' is set to True for my object. How can I achieve this and chain together other events based ...

Using jQuery with Angular 4 allows for powerful front-end development

To include jQuery in an Angular4 project, I follow these steps: npm install --save jquery npm install --save-dev @types/jquery In the app.component.ts file import $ from 'jquery'; or import * as $ from 'jquery'; When running "ng se ...

Encountering difficulty retrieving host component within a directive while working with Angular 12

After upgrading our project from Angular 8 to Angular 12, I've been facing an issue with accessing the host component reference in the directive. Here is the original Angular 8 directive code: export class CardNumberMaskingDirective implements OnInit ...

Why is it that when using the same Angular project and packages on different computers, errors only occur on one of them?

In my professional setup, I have the following installed: Windows 7 Visual studio 2015 (with typescript 2 installed) Resharper 2016.3.2 npm version 3.10.10 Node v 6.10.0 These are the global packages installed: npm -g list --depth=0 +-- @angular/<a ...

Exploring the Impact of 2 HostBindings on Class Generation from Inputs in Angular 4

I'm struggling with the code in my component, which looks like this: @Component({ selector: "home", templateUrl: "./home.html" }) export class Home { constructor() {} @HostBinding("class") @Input() public type: string = "alert" @HostBindi ...

What's the best way to integrate redux-persist into a TypeScript project?

Having some difficulty adding redux-persist to my React project (in typescript). The compilation is failing with the following error message: Could not find a declaration file for module 'redux-persist/lib/storage'. '.../WebstormProjects/c ...

Node.js built-ins require shims, while global variable names are absent

After updating my project using npm-check-updates, I encountered a strange error that stumped me. Despite following the suggested terminal command to install polyfill-node, the issue persisted with no resolution in sight online. The error displayed on the ...

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...

Is it possible to preserve the numerical type of a percentage when applying number formatting?

After applying number formatting, I converted a numerical value of 150 to 150.00%. Although this is the desired display format with the percentage sign included, the data type remains as string instead of number. Is there a method to convert it back to a ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

Transform a specialized function into a generic function with static typing

First off, I have a network of routes structured like this: interface RouteObject { id: string; path: string; children?: RouteObject[]; } const routeObjects: RouteObject[] = [ { id: 'root', path: '/', children: [ ...

Navigating through Angular using Typescript can sometimes lead to uncertainty when working with return data. This is where the

How do you handle a request with uncertain data and type checking? For instance, if you are making an HTTP call to an API where various data can be returned, but your component requires a specific data structure defined by an interface. Here's a sim ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

What is the rationale behind permitting surplus properties in Typescript interfaces even though all properties are declared as optional?

Exploring the code snippet... interface Options { allowed?: string; } function test(options: Options) { return options; } const options = { allowed: 'allowed', notAllowed: 'notAllowed', }; test(options); // no error thrown ...

Angular - Leveraging Jest and NgMocks to Mock Wrapper Components

Within our project, we have implemented a feature where user roles can be assigned to various elements in the application. These roles determine whether certain elements should be disabled or not. However, due to additional conditions that may also disable ...