TypeORM:查找列值在数组中的行
这篇简短而直截了当的文章向您展示了在 TypeORM 中使用WHERE IN查询的 2 种不同方法(以防您要搜索其列值是给定数组的元素的行)。第一种方法是使用 findBy() 方法,而第二种方法是使用查询构建器。
在接下来的示例中,我们将使用名为Product的实体:
// Product entity
import {
Entity,
PrimaryGeneratedColumn,
Column,
} from 'typeorm';
@Entity({name: 'products'})
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
color: string;
@Column({default: 0})
price: number
}
使用 findBy() 方法
假设我们要检索颜色为以下颜色的产品:蓝色、红色、橙色和绿色。我们将执行以下操作:
- 导入In运算符:
import { In } from 'typeorm';
- 像这样调用findBy() 方法:
const productRepository = dataSource.getRepository(Product);
// find products
const products = await productRepository.findBy({
color: In(['blue', 'red', 'orange', 'green'])
})
这将执行此查询:
SELECT * FROM "products" WHERE "color" IN ('blue','red','orange','green')
使用查询生成器
它也会在某个列表中找到带有颜色的产品,但这次我们使用 QueryBuilder:
const productRepository = dataSource.getRepository(Product);
const products = await productRepository
.createQueryBuilder('product')
.where('product.color IN (:...colors)', {
colors: ['blue', 'red', 'orange', 'green'],
})
.getMany();
console.log(products);
此代码将执行与前面示例相同的查询:
SELECT * FROM "products" WHERE "color" IN ('blue','red','orange','green')
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。