我在我的node.js项目中使用了TypeOrm。我知道要从数据库中找到一条记录,我可以这样做:
userRepository.find({ where: { firstName: "John" } });
它执行查询:
SELECT * FROM "user"
WHERE "firstName" = 'John'
但现在我需要在"where“条件中添加另一个字段,只有在出现值的情况下。例如,我还想检查SQL "where“条件中的company
,但仅当出现company
值时才检查。
我尝试了一下,我想知道我是否可以通过给出一个默认的空字符串''
来执行以下操作
const company = params.company ? params.company : '';
userRepository.find({ where: { firstName: "John", company: company } });
但是它仍然会在最终的SQL查询中添加"company"=''
,这是不好的。我想知道在TypeORM中有没有一个现有的函数,如果提供了值而不是空字符串,那么它可以动态地决定只在where
中添加更多的条件?
发布于 2021-11-22 05:21:34
你可以对它使用销毁。例如:
userRepository.find({
where: {
firstName: "John",
...(params?.company && { company: params.company }),
}
});
因此,如果params.company
为undefined
(或空字符串),则
...(undefined && { company: undefined })
返回undefined
,对于销毁,它就像...{}
一样返回给你。
如果params.company
包含一些值,则
...('company' && { company: 'company' })
返回...{company: 'company'}
并为你的where析构它。
示例:
const companyTestWithValue = 'company';
const companyTestWithoutValue = '';
const whereWithValue = {
firstName: 'John',
...(companyTestWithValue && { company: companyTestWithValue }),
};
const whereWithoutValue = {
firstName: 'John',
...(companyTestWithoutValue && { company: companyTestWithoutValue }),
};
console.log('whereWithValue:', whereWithValue);
console.log('whereWithoutValue:', whereWithoutValue);
发布于 2021-11-22 05:06:10
我不认为会有一个很好的解决方案。您最好的选择可能就是使用if - else语句。TypeOrm将使用传递给它的任何内容创建一条语句。我建议你这样做:
if(params.company){
userRepository.find({ where: { firstName: "John", company: company } });
} else{
userRepository.find({ where: { firstName: "John" } });
}
发布于 2021-11-22 05:15:59
您可以动态创建查找条件,例如:
const condition = { where: { firstName: "John" } };
if (params.company) {
condition.where = {
...condition.where,
company: params.company
}
}
const user = userRepository.find(condition);
https://stackoverflow.com/questions/70065624
复制相似问题