Sequelize: Find All That Match Contains (Case Insensitive)

后端 未结 2 2075
既然无缘
既然无缘 2021-02-08 02:40

I want to use sequelize.js to query a model for records with a contains restraint. How do I do that?

This is what I have right now:

Assets
  .findAll({ l         


        
相关标签:
2条回答
  • 2021-02-08 02:51
    Assets.findAll({
            limit: 10,
            where: {
                asset_name: {
                    [Op.like]: '%' + request.body.query + '%'
                }
            }
    }).then(function(assets){
        return response.json({
            msg: 'search results',
            assets: assets
        });
    }).catch(function(error){
        console.log(error);
    });
    

    EDIT

    In order to make it case insensitive, you could use the LOWER sql function, but previously you would also have to lower case your request.body.query value. Sequelize query would then look like that

    let lookupValue = request.body.query.toLowerCase();
    
    Assets.findAll({
        limit: 10,
        where: {
            asset_name: sequelize.where(sequelize.fn('LOWER', sequelize.col('asset_name')), 'LIKE', '%' + lookupValue + '%')
        }
    }).then(function(assets){
        return response.json({
            msg: 'message',
            assets: assets
        });
    }).catch(function(error){
        console.log(error);
    });
    

    What it does is to lower case your asset_name value from table, as well as lower case the request.body.query value. In such a case you compare two lower cased strings.

    In order to understand better what is happening in this case I recommend you take a look at the sequelize documentation concerning sequelize.where(), sequelize.fn() as well as sequelize.col(). Those functions are very useful when trying to perform some unusual queries rather than simple findAll or findOne.

    The sequelize in this case is of course your Sequelize instance.

    0 讨论(0)
  • 2021-02-08 02:54

    If you are using sequlize better to use [Op.iLike]: `%${request.body.query}%` and you can forget about the sequlize functions.

    0 讨论(0)
提交回复
热议问题