question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Question] How to load relation and count entity and map it so it is not nested?

See original GitHub issue

Hi, I’m wondering if its possible to map the count of an entity’s relation to a custom property.

The reason for this is I’m also trying to load another relation .loadRelationCountAndMap('script.sessions', 'script.sessions') that is removing the data count from ever appearing.

Secondly, I am trying to return a specific format of entity counts that are not nested so I can easily convert them into single series data for d3 charts without over complicated logic.

If I change the loadRelationCountAndMap to (‘script.sessionsCount’, ‘script.sessions’) I can get the session count and data will appear however it is still nested within sessions and then I am returning a ‘sessionsCount’ instead of ‘sessions’.

Maybe I am taking the wrong approach? Thanks.

Expected

[
    {
        "id": 1,
        "name": "Script Name",
        "author": {
            "id": 1,
            "username": "Username"
        },
        "data": 4,
        "users": 1
    }
]

Actual

[
    {
        "id": 1,
        "name": "Script Name",
        "author": {
            "id": 1,
            "username": "Username"
        },
        "sessions": [
            {
                "data": 4
            }
        ],
        "users": 1
    }
]
    async getCount(): Promise<Script[]> {
        return await this.scriptRepository
            .createQueryBuilder('script')
            .leftJoinAndSelect('script.author', 'author')
            .leftJoinAndSelect('script.sessions', 'sessions')
            .loadRelationCountAndMap('script.users', 'script.users')
            .loadRelationCountAndMap('script.data', 'sessions.data')
            .select('script.name')
            .addSelect('script.id')
            .addSelect('author.id')
            .addSelect('author.username')
            .getMany();
    }
@Entity()
export class Script {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ unique: true })
    name: string;

    @ManyToOne(type => User, user => user.created)
    author: User;

    @ManyToMany(type => User)
    @JoinTable()
    users: User[];

    @OneToMany(type => Session, session => session.script)
    sessions: Session[];
}

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:20 (7 by maintainers)

github_iconTop GitHub Comments

85reactions
pleerockcommented, Apr 18, 2018

don’t harm yourself and your machine and execute a separate queries

33reactions
Tyler-Vcommented, Jul 11, 2018

So after many attempts, this is what I came up with that seems to product the desired output, do you see any ways to improve this or is this syntax acceptable?

    async findScriptsByAuthorId(authorId: number): Promise<any> {
        return await this.scriptRepository
            .createQueryBuilder('script')
            .leftJoin('script.author', 'author')
            .leftJoin('script.users', 'users')
            .leftJoin('script.sessions', 'sessions')
            .where('author.id = :id', { id: authorId })
            .select('script.id', 'id')
            .addSelect('script.name', 'name')
            .addSelect('script.key', 'key')
            .addSelect('script.created', 'created')
            .addSelect('COUNT(DISTINCT(users.id)) as users')
            .addSelect('COUNT(DISTINCT(sessions.id)) as sessions')
            .groupBy('script.id')
            .getRawMany();
    }
[
    {
        "id": 1,
        "name": "Script Name",
        "key": "130bbbf9-5c17-488f-8143-dba67a20d512",
        "created": "2018-05-09T14:06:08.933Z",
        "users": "1",
        "sessions": "10"
    },
    {
        "id": 2,
        "name": "Test",
        "key": "45ceb0d9-a3bc-4278-817b-4da2dc4e949b",
        "created": "2018-07-10T22:46:42.649Z",
        "users": "0",
        "sessions": "0"
    }
]

Only issue I have with it now is COUNT() is being returned as a string “10” instead of a number, are there anyways around this? Is this related to https://github.com/typeorm/typeorm/issues/1875

Read more comments on GitHub >

github_iconTop Results From Across the Web

[Question] How to load relation and count entity and map it so ...
Hi, I'm wondering if its possible to map the count of an entity's relation to a custom property. The reason for this is...
Read more >
How to filter and count relation items in typeorm?
1st argument is the property name the count would be mapped to - that would be a field on your entity that is...
Read more >
Eager and Lazy Relations - typeorm - GitBook
Eager relations are loaded automatically each time you load entities from the database. For example: import { Entity, PrimaryGeneratedColumn, Column, ...
Read more >
Where are the lines drawn? - All About Redistricting
When that happens, the entity drawing the lines has the discretion to take criteria into account, and resolve conflicts where they arise, as...
Read more >
Relationship Loading Techniques
The one case where SQL is not emitted is for a simple many-to-one relationship, when the related object can be identified by its...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found