I have this entity declaration with the virtual column slugWithUuid. How can I query this kind of column within a query.
@Entity()
export class Course extends DefaultCredential {
@Column({ type: 'varchar', length: 75 })
title: string;
@Column({ type: 'varchar', length: 50 })
slug: string;
@Column({ type: 'json', nullable: true })
additionalInfoJSON: any;
slugWithUuid: string;
@AfterLoad()
setCustomProperty() {
this.slugWithUuid =
this.slug + '-' + JSON.parse(this.additionalInfoJSON)?.uuid;
}
@BeforeInsert()
insertShortUUID() {
const shortUUID = generateUUID(6);
const additionalInfo = {
...this.additionalInfoJSON,
uuid: shortUUID,
};
this.additionalInfoJSON = JSON.stringify(additionalInfo);
}
}
This is an example of my query:
async findBySlug(slug: string) {
const entity = await this.repos.findOne({
where: { slugWithUuid: slug }
});
if (!entity) {
throw new NotFoundException('Entity not found with this slug');
}
return entity;
}
Is there any other way to declare this virtual column to be able to filter it within a query, because this query return me this error for the moment:
[Nest] 637270 - 10/03/2024, 9:37:42 AM ERROR [ExceptionsHandler] Property "slugWithUuid" was not found in "Course". Make sure your query is correct. EntityPropertyNotFoundError: Property "slugWithUuid" was not found in "Course". Make sure your query is correct.
After a long research, I found out this solution:
@VirtualColumn({
query: (alias) => {
const uuidSelect = `JSON_UNQUOTE(JSON_EXTRACT(JSON_UNQUOTE(${alias}.additionalInfoJSON), '$.uuid'))`;
return `CONCAT(
${alias}.slug,
'-',
${uuidSelect}
)`;
},
})
slugWithUuid: string;
It re-declare slugWithUuid with @VirtualColumn and now I can query it.