将条件包括在条件中

时间:2019-06-10 06:35:30

标签: sql node.js sequelize.js

我在查询带有where条件的多个include时遇到问题。

使用直接查询sql对其进行了尝试,效果很好。我使用sql制作了一个示例,并在使用sequelize查询将其转换为node.js时遇到问题。

这是正确的SQL

SELECT pr.id, pr.component_id, pr.requirement_type_id, c.name, rt.name
FROM product_requirements as pr
LEFT JOIN components as c
ON pr.component_id = c.id
LEFT JOIN requirement_types as rt
ON pr.requirement_type_id = rt.id
WHERE c.name LIKE '%Product%'
OR rt.name LIKE '%Product%';

我尝试过将其转换为序列化,这是我到目前为止所做的,但始终会出现错误或正确的结果

let query = {
    where : {
        [Op.or] : [
            {component.name : { [Op.like] : `%${keyword}%` }},
            {requirement.name : { [Op.like] : `%${keyword}%` }}
        ]
    },
    include : [
        {
            model : models.components,
            as : 'component'
        },
        {
            model : models.requirement_types,
            as : 'requirement'
        }
    ]
}

我希望它能像sql结果一样

2 个答案:

答案 0 :(得分:0)

我认为在其中的查询不理解别名

var where = {
    [Op.or]: [
        sequelize.literal(`[components].name like "%${keyword}%"`),
        sequelize.literal(`[requirement_types].name like "%${keyword}%"`)
    ]
};
var include = [
    {
        model: models.components,
        as: 'component'
    },
    {
        model: models.requirement_types,
        as: 'requirement'
    }
];
product_requirements.findAll({
    where: where,
    include: include

}).then(results => {
});

答案 1 :(得分:0)

发现我们需要添加required: false使其生效并像这样进行编码。

let where = {
    product_id : productId,
        [Op.or] : [
            {"$component.name$" : {[Op.like] : `%${keyword}%`}},
            {"$requirement_type.name$" : {[Op.like] : `%${keyword}%`}}
        ]
    }
    let include = [
        { model: models.components, required: false },
        { model: models.requirement_types, required: false }
    ]
    query = {
        where : where,
        include : include
    }

models.product_requirements.findAll(query)
        .then((result) => {
            res.status(200).send({
                data : result
            })
        })
        .catch((err) => {
            res.error(err)
        })