saiful haqqi
saiful haqqi

Reputation: 95

Sequelize where condition from join result

i have table product, and the relation are product belong to category, product belong to outlet, and product belong to market. now i need to search product with name like %keyword% OR outlet name like %keyword% OR category name like %keyword% it is possible to where condition after join table?

let where = {
        active: true,
        [Op.or]: [
            { name: { [Op.like]: '%' + keyword + '%' } },
            { 'category.name': { [Op.like]: '%' + keyword + '%' } },
            { 'outlet.name': { [Op.like]: '%' + keyword + '%' } },
        ]
    }
let inWhere = { active: true };
model.findAll({
    attributes: ['name'],
    where,
    include: [
        {
            required: false,
            model: db.category,
            as: 'category',
            where: inWhere,
            attributes: ['name']
        },
        {
            required: false,
            model: db.outlet,
            as: 'outlet',
            where: inWhere,
            attributes: ['name', 'city']
        },
        {
            required: false,
            model: db.market,
            as: 'market',
            where: { active: true },
            attributes: ['name']
        }
    ]
})

Upvotes: 0

Views: 740

Answers (1)

Soham Lawar
Soham Lawar

Reputation: 1265

Yes, it is possible. Your where clause should be as follows -

where: {
  [Op.or]: [
    { name: { [op.like]: '%${keyword}%' } },
    { '$`category`.`name`$': { [op.like]: '%${keyword}%' } },
    { '$`outlet`.`name`$': { [op.like]: '%${keyword}%' } }
  ]
},

Hope it helps!

Upvotes: 1

Related Questions