我正在尝试按顺序执行查询,其中必须根据请求参数在何处添加条件
router.get("/getsearchdata",(req, res) => {
var searchquery =[
{model:ProvidersCategories,attributes:["category_id"],
include: [
{model:Categories,attributes:["category_id","category_name"]},
]
}
]
if(req.query.agency && req.query.agency!=''){
searchquery.where = {
$and: [
{agencyName: {$like: '%' + req.query.agency + '%'}},
]
}
}
Providers.findAll({
include:searchquery
}).then(providerData =>{
if(!providerData) {
res.status(404).send({reason:'no data found'});
} else {
res.status(200).send(providerData);
}
});
});
我有三个表“ providers”,“ categories”和“ provider_Categories”。我正在尝试加入三个表并获取提供者。
在请求即要求中,如果存在输入req.query.agency != ''
,则必须添加if条件,如果输入where agencyName like "% + req.query.agency + %"
,则不应有if条件。为此,我尝试了上面的代码。但是,即使输入req.query.agency == ''
有条件的地方写什么正确的方法
答案 0 :(得分:1)
您的变量searchquery
是一个数组,您无法为其分配where
属性。您应该做的就是将where
对象传递给查询选项对象:
router.get("/getsearchdata", (req, res) => {
var whereClause;
if (req.query.agency && req.query.agency != '') {
whereClause = {agencyName: {$like: '%' + req.query.agency + '%'}};
}
Providers.findAll({
include: [
{
model: ProvidersCategories, attributes: ["category_id"],
include: [
{model: Categories, attributes: ["category_id", "category_name"]},
]
}
],
where: whereClause
}).then(providerData => {
if (!providerData) {
res.status(404).send({reason: 'no data found'});
} else {
res.status(200).send(providerData);
}
});
});