typeOrm 在 where 子句中使用条件

发布于 2025-01-10 19:47:47 字数 603 浏览 0 评论 0原文

@Injectable()

导出类 WeightPriceService { 构造函数(readonly 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”参数是否为 true 我想检查“type:tariffType”,否则不想检查“type”

@Injectable()

export class WeightPriceService {
constructor(readonly 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;
}

}

Is "tariffType" parameter is true I would like to check "type:tariffType" else do not want to check "type"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

無處可尋 2025-01-17 19:47:47

您可以使用展开运算符来实现此目的。

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;
}

You can use the spread operator for this.

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);

When the condition is True it will inject the object otherwise wouldn't add anything.

In your case it would be

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文