基于条件的where条件在续结Node JS中

时间:2019-07-11 12:05:54

标签: node.js sequelize.js sequelize-typescript

我正在尝试按顺序执行查询,其中必须根据请求参数在何处添加条件

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 == ''

,where条件也不会与主查询连接在一起

有条件的地方写什么正确的方法

1 个答案:

答案 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);
            }
        });
    });