[Question] How to load relation and count entity and map it so it is not nested?
See original GitHub issueHi, 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:
- Created 5 years ago
- Comments:20 (7 by maintainers)
don’t harm yourself and your machine and execute a separate queries
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?
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