简体   繁体   中英

Sequelize PostgreSQL: query to see if string is within an array

Given that I have a model called Model with a column called items which holds an array of strings, how can I query to see whether a string queryString is in the array or has a similar element in the array?

Example:

items: ["cat", "dog", "bird", "turtle", "doe" ]

queryString = ["%do%","%b"]

Should return :

animalArray = ["dog", "doe", "bird"]


Edit: Is there anyway to pair up an $overlap with $iLike somehow?

Model.findAll({
    where: {
        items: { $in: { $iLike: { $any: queryString } } }
    }
}).then(function(array){
    // Do whatever here with array
})

$iLike is a special Postgres thing in Sequelize

Thanks!

Try this solution.

Create a new array which stored your like conditions 创建一个新数组,存储您的条件

var conditions = [];

var queryString = ["%do%","%b"];

loop your queryString values 循环查询字符串值

for(var x in queryString) {
    // do something
}

inside loop just append your $like condition 内部循环只需附加您的$like条件

conditions.push({
    items: {
        $like: queryString[x]
    }
});

So your array would be like this

[{
    items: {
        $like: "%do%"
    }
},{
    items: {
        $like: "%b"
    }
}]

So your sequelize query would be like this

var conditions = [];
var queryString = ["%do%","%b"];

for(var x in queryString) {
    conditions.push({
        items: {
            $like: queryString[x]
        }
    });
}

Model.findAll({
    where: {or: conditions}
}).then(function(array){
    // Do whatever here with array
})

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