I have an entity
@Entity()
export class BookEntity {
@PrimaryGeneratedColumn()
@Generated("increment")
public id: number
@CreateDateColumn()
public createdAt: Date
@Column()
public title: string
@Column()
public author: string
@Column({ type: "simple-array" })
public category: string[]
@Column({ default: "" })
public cover: string
@Column()
public issueDate: string
@Column({ default: 0 })
public liked: number
@Column({ default: 0 })
public downloads: number
@Column({ default: 0 })
public views: number
@Column({ type: "simple-array" })
public path: string
}
And I need to get entities filtered by value from column category e.g. If entity has categories ["test1", "test2", "test3"], I would like to be able get all entities with category "test2" What should I do for it, please help :)
I already created service for getting paginated list of all book_entity
public async getBooks(page: number): Promise<PageDto<BookEntity>> {
try {
const queryBuilder = this.bookRepository.createQueryBuilder("book_entity")
queryBuilder.take(10)
const itemCount = await queryBuilder.getCount()
const { entities } = await queryBuilder.getRawAndEntities()
const pageData = new PageDto<BookEntity>(entities, itemCount, page)
return pageData
} catch (error) {
console.log("Getting books error: ", error)
}
}
But what should I change for getting by category? I know that queryBuilder has .orderBy method, but I don't know how use it for my target
You can filter your query using where
or andWhere
(if you need multiple filters)
const queryBuilder = this.bookRepository.createQueryBuilder("book_entity")
queryBuilder.where('book_entity.category IN (:...category)', { category: ['"test2"'] })
Refer to https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#adding-where-expression for more advanced use-cases.