Skip to content
Advertisement

Sequelize Include with Where Condition

I’m having a problem with how to query multiple include with where condition.

Tried it using direct query to sql and it works fine. I made a sample using sql and having a problem converting it to node.js with sequelize query.

This is the correct 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%';

I tried it to convert it to sequelize and this is what I’ve done so far but it keeps getting error or correct results

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'
        }
    ]
}

I expected it to get like what the sql result is

Advertisement

Answer

Found out that we neeed to add required: false to make it work and code it like this.

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)
        })
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement