简体   繁体   中英

Sequelize - Querying string field with array of strings as input

I have records created in the below manner:

{id: 1, units: 'unit 1,unit 2,unit 3' } {id: 2, units: 'unit 2,unit 3' } {id: 3, units: 'unit 2' }

I need to get the records with respect to units.

req.query.unit_name = 'unit 1,unit 2'; or req.query.unit_name = 'unit 2,unit 1';

req.query.unit_name = req.query.unit_name.split(',');

model: unitModel.js

module.exports = (sequelize, DataTypes) => {
    const unitModel = sequelize.define(
        id: {
            type: DataTypes.UUID,
            primaryKey: true
        },
        units: {
            type: DataTypes.STRING
        }
    );
    return unitModel;
}

sequelize query:

db.unitModel.findAll({
    where: {
        units: {
            [Op.in]: req.query.unit_name
        }
    }
})

Can anyone help me how to get the records for string field using array of strings as input???

You can split 'req.query.unit_name' into array on ','.

const unitName = req.query.unit_name.split(',');
db.unitModel.findAll({
where: {
    units: {
        [Op.in]: unitName
    }
}
});

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM