I have two entities image and tag with many to many relationship
@Entity()
export class Image {
@PrimaryGeneratedColumn()
id: number;
@Column('text', { nullable: true })
caption: string;
@Column('text', { nullable: false })
url: string;
@Column('text', { nullable: false })
thumbnailUrl: string;
@ManyToOne(() => User, {
eager: true,
})
uploader: User;
@JoinTable()
@ManyToMany(() => Tag, (tag: Tag) => tag.images, {
cascade: true,
eager: true,
})
tags?: Tag[];
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
and Tag entity
@Entity()
export class Tag {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(() => Image, (image) => image.tags)
images: Image[];
}
Now I want to fetch popular tags. For that take 10 tags that have highest number of images created in last 7 days. For this i tried following in tag.repository.ts
getPopular() {
return (
this.createQueryBuilder('tag')
.addSelect((query) => {
return query
.select('COUNT(I.id)', 'count')
.from('image', 'I')
.where('I.created_at > :date', {
date: DateTime.now().minus({ weeks: 1 }).toISODate(),
});
}, 'imagecount')
.orderBy('imagecount', 'DESC')
.take(10)
.getMany()
);
But this will count all images that are created in last 7 days and will not consider if the image has that tag or not. So how should I load relation so that it count images with tags?