从 TypeORM 存储库中获取许多,而不仅仅是一个
getMany from a TypeORM Repository instead of just one
我有这段代码可以从 TypeORM 存储库中获取一本书,并且工作正常。
public async getBook(name: string) {
const book = this.bookRepository.findOne({
where: [{ name: name }],
});
return book;
}
但是,我想实现某种 GetManyBooks,在其中我将名称列表作为字符串使用 find 关键字而不是 findone 和 return 它。我认为它会类似,但我无法在网上找到任何关于此的文档。
public async getManyBooks(name: string[]) {
const book = this.bookRepository.find({
where: [{ name: name }],
});
return book;
}
有没有更好的方法来解决这个问题?
可以使用typeorm提供的in
运算符。 Here are the docs
另外我建议你不要使用 async
因为你不使用 await
而只是 return 承诺本身。这会给你一个 Promise<Book[]>
.
import { In } from "typeorm";
// docs example
const loadedPosts = await connection.getRepository(Post).find({
title: In(["About #2", "About #3"]),
});
// In your case
public getManyBooks(name: string[]) {
return this.bookRepository.find({
where: {name: In(name)},
});
}
我有这段代码可以从 TypeORM 存储库中获取一本书,并且工作正常。
public async getBook(name: string) {
const book = this.bookRepository.findOne({
where: [{ name: name }],
});
return book;
}
但是,我想实现某种 GetManyBooks,在其中我将名称列表作为字符串使用 find 关键字而不是 findone 和 return 它。我认为它会类似,但我无法在网上找到任何关于此的文档。
public async getManyBooks(name: string[]) {
const book = this.bookRepository.find({
where: [{ name: name }],
});
return book;
}
有没有更好的方法来解决这个问题?
可以使用typeorm提供的in
运算符。 Here are the docs
另外我建议你不要使用 async
因为你不使用 await
而只是 return 承诺本身。这会给你一个 Promise<Book[]>
.
import { In } from "typeorm";
// docs example
const loadedPosts = await connection.getRepository(Post).find({
title: In(["About #2", "About #3"]),
});
// In your case
public getManyBooks(name: string[]) {
return this.bookRepository.find({
where: {name: In(name)},
});
}