typeOrm 在 where 子句中使用条件
typeOrm using condition in where clause
@Injectable()
导出class权重价格服务{
构造函数(只读 dbContext:DbContext){}
async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
const { price } = await this.dbContext.tariffs.findOne({
where: {
type: tariffType ? tariffType : ,
isActive: true,
weight: { min: LessThan(weight), max: MoreThan(weight) },
},
relations: ['weight'],
});
return price;
}
}
“tariffType”参数是否为真我想检查“type:tariffType”否则不想检查“type”
您可以为此使用 spread operator。
const obj = {
...(true && {my: 'obj'})
};
const truly = 1 === 1;
const falsy = 1 !== 1;
const myObject = {
foo: 'bar',
...(truly && {my: 'data'}),
...(falsy && {other: 'data'}),
something: 'else'
};
console.log(myObject);
当条件为 True
时它将注入对象,否则不会添加任何东西。
你的情况是
async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
const { price } = await this.dbContext.tariffs.findOne({
where: {
...(tariffType && { type: tariffType }),
isActive: true,
weight: { min: LessThan(weight), max: MoreThan(weight) },
},
relations: ['weight'],
});
return price;
}
@Injectable()
导出class权重价格服务{ 构造函数(只读 dbContext:DbContext){}
async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
const { price } = await this.dbContext.tariffs.findOne({
where: {
type: tariffType ? tariffType : ,
isActive: true,
weight: { min: LessThan(weight), max: MoreThan(weight) },
},
relations: ['weight'],
});
return price;
}
}
“tariffType”参数是否为真我想检查“type:tariffType”否则不想检查“type”
您可以为此使用 spread operator。
const obj = {
...(true && {my: 'obj'})
};
const truly = 1 === 1;
const falsy = 1 !== 1;
const myObject = {
foo: 'bar',
...(truly && {my: 'data'}),
...(falsy && {other: 'data'}),
something: 'else'
};
console.log(myObject);
当条件为 True
时它将注入对象,否则不会添加任何东西。
你的情况是
async findPriceByWeight(weight: number, tariffType?: PackageMaterialType): Promise<number> {
const { price } = await this.dbContext.tariffs.findOne({
where: {
...(tariffType && { type: tariffType }),
isActive: true,
weight: { min: LessThan(weight), max: MoreThan(weight) },
},
relations: ['weight'],
});
return price;
}