I have 2 entities like the ones below. My question is what is the easiest / most efficient way to return the number of total votes that are linked to a given post?
A PostVote has an enum vote that can be either Up or Down.
I was thinking about using the serializer, but you would still return all of the PostVote rows just to get a count essentially.
Should I just do separate em.count() queries or is there a better way?
@Entity()
export class Post extends Node<Post> {
@ManyToOne(() => User, { wrappedReference: true })
user: IdentifiedReference<User>;
@Property({ columnType: 'text' })
title: string;
@Property({ columnType: 'text', nullable: true })
description?: string;
@OneToMany(() => PostVotes, (pv) => pv.post, {
serializer: (v: PostVotes[]) => {
const upVotes = v.filter((v2) => v2.vote.Up).length;
const downVotes = v.filter((v2) => v2.vote.Down).length;
return upVotes - downVotes;
},
})
votes = new Collection<PostVotes>(this);
@Entity()
export class PostVotes extends BaseEntity<
PostVotesConstructorValues & PrivatePostVotesProperties,
'post' | 'user'
> {
@ManyToOne(() => Post, { wrappedReference: true, primary: true })
post: IdentifiedReference<Post>;
@ManyToOne(() => User, { wrappedReference: true, primary: true })
user: IdentifiedReference<User>;
[PrimaryKeyType]?: [IdentifiedReference<User>, IdentifiedReference<User>];
@Enum({ items: () => PostVote })
vote = PostVote;